Johan
Johan

Reputation: 899

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?

Upvotes: 11

Views: 64772

Answers (3)

user3499663
user3499663

Reputation: 9


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
}

Upvotes: 0

bigahega
bigahega

Reputation: 415

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.

Upvotes: 10

David C. Rankin
David C. Rankin

Reputation: 84551

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

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)

Upvotes: 4

Related Questions