简体   繁体   English

C 从第 x 行到第 y 行读取文件

[英]C Read a file from line x to line y

I am a beginner in C, and I would like to know if there is a way to read a file from one line to another for example from the 10th to the 20th.我是 C 的初学者,我想知道是否有办法将文件从一行读取到另一行,例如从 10 号到 20 号。 I searched several times, and only found methods to read files line by line找了几遍,只找到了逐行读取文件的方法

In most modern environments, the concept of a line is a convention whereby the character 0xa (ascii linefeed) denotes the end of a line.在最现代的环境中,线的概念是一种惯例由此字符是0xA(ASCII换行)表示的线的端部。 Some CPM-derived systems have an anachronism which insists a 0xd (ascii carriage return) before the end of line character.一些 CPM 派生系统有一个时代错误,它在行尾字符之前坚持 0xd(ascii 回车)。 In even older environments, a line was a record of 80 bytes, corresponding to a solitary punch card.在更旧的环境中,一行是 80 字节的记录,对应于一张单独的穿孔卡片。

In older, fixed record systems, line 10 was at offset 10*80 = 800 in the file.在较旧的固定记录系统中,第 10 行在文件中的偏移量为 10*80 = 800。 In newer, stream -oriented io [ btw, newer here refers to the late 1970s ], you cannot calculate the line location without examining the file contents.在较新的、面向的 io [顺便说一句,这里的较新指的是 1970 年代后期],您无法在不检查文件内容的情况下计算行位置。 So, as others commented, you have to read and ignore the lines you do not want.因此,正如其他人评论的那样,您必须阅读并忽略您不想要的行。 If it is critical for multiple queries of the same file, build an index of line locations and use it.如果它对同一文件的多个查询至关重要,请构建行位置索引并使用它。

#include <stdio.h>
#include <stdlib.h>

#define FIRST_LINE (3)
#define LAST_LINE (7)

#define FILE_NAME "lines.txt"

int main(void) {
    char buffer[BUFSIZ];
    FILE * file;
    int line;

    file = fopen(FILE_NAME, "r");
    if ( file == NULL ) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    line = 0;
    while ( fgets(buffer, BUFSIZ, file) != NULL ) {
        if ( ++line < FIRST_LINE )
            continue;
        else if ( line > LAST_LINE )
            break;
        else
            printf("%s", buffer);
    }

    if ( fclose(file) ) {
        perror("fclose");
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}

lines.txt:行.txt:
I am a beginner in C,我是 C 的初学者,
and I would like to know我想知道
if there is a way to read如果有一种阅读方式
a file from one line一行中的一个文件
to another for example from到另一个例如从
the 10th to the 20th. 10 日到 20 日。
I searched several times,找了好几遍
and only found methods并且只找到方法
to read files line by line.逐行读取文件。
Know someone who can answer?知道谁可以回答?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM