简体   繁体   中英

Reading text-file until EOF using fgets in C

what is the correct way to read a text file until EOF using fgets in C? Now I have this (simplified):

char line[100 + 1];
while (fgets(line, sizeof(line), tsin) != NULL) { // tsin is FILE* input
   ... //doing stuff with line
}

Specifically I'm wondering if there should be something else as the while-condition? Does the parsing from the text-file to "line" have to be carried out in the while-condition?

According to the reference

On success, the function returns str . If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).

So checking the returned value whether it is NULL is enough. Also the parsing goes into the while-body.

What you have done is 100% OK, but you can also simply rely on the return of fgets as the test itself, eg

char line[100 + 1] = "";  /* initialize all to 0 ('\0') */

while (fgets(line, sizeof(line), tsin)) { /* tsin is FILE* input */
    /* ... doing stuff with line */
}

Why? fgets will return a pointer to line on success, or NULL on failure (for whatever reason). A valid pointer will test true and, of course, NULL will test false .

( note: you must insure that line is a character array declared in scope to use sizeof line as the length. If line is simply a pointer to an array, then you are only reading sizeof (char *) characters)


i had the same problem and i solved it in this way

while (fgets(line, sizeof(line), tsin) != 0) { //get an int value
   ... //doing stuff with line
}

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