简体   繁体   中英

printing specific lines from files in C

So, I'm writing a small utility to help me read some files more efficiently, so the program opens a file then prints everything from line 12 till the end. I'm using Windows. So far this is my code:

FILE* file = fopen(argv[1], "rb");
    char chr;
    long long ln = 1;
    if (file) {
        while ((chr = fgetc(file)) != -1) {
            if (chr == '\n') ln += 1;
            if (ln >= 12)
                printf("%c", chr);
        }
        fclose(file);
        return 0;
    }
    else {
        return 1;
    }

But every time I run the program it gives me something like this:

X:\example>readln document.txt

line 12
line 13
line 14
...

As you can see for some reason it always has this empty line at the beginning for no reason. Please help me solve this.

Two bugs:

First, fgetc() returns an int , not a char , because it needs to return every possible character value as well as the extra value EOF. This value is often -1, but since you are chopping the return value into a char , the program will also stop when it encounters the character 0xFF (which it will probably never do with a text file, so this bug is well-hidden).

Secondly, you're incrementing the line number when seeing a '\\n' , then printing a character at a time. When the 12th line is reached, that will print the '\\n' at the end of the 11th line. Move the increment down a line after the print.

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