简体   繁体   中英

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. 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. Some CPM-derived systems have an anachronism which insists a 0xd (ascii carriage return) before the end of line character. In even older environments, a line was a record of 80 bytes, corresponding to a solitary punch card.

In older, fixed record systems, line 10 was at offset 10*80 = 800 in the file. In newer, stream -oriented io [ btw, newer here refers to the late 1970s ], you cannot calculate the line location without examining the file contents. 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:
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.
I searched several times,
and only found methods
to read files line by line.
Know someone who can answer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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