reading from a text file

G

Giorgos Keramidas

googler said:
One more question. My code looks like:
while (!feof(fp))
{
fgets(str, 120, fp);
printf("%s", str);
}

This prints the last line twice. I don't understand why. When
it prints the last line for the first time, it should have
known that the end of the file has been reached, so the next
condition check for the while loop should have failed. Why is
it still entering the while loop and printing the last line
again?

1. When fgets() reads the last line of text, you go ahead and
print it.

2. Then you loop back. EOF hasn't been triggered yet for the
input file.

3. You call fgets() again. The return value of fgets() is NULL
and EOF is signalled on the input stream, but you ignore the
return code of fgets() and go ahead to print whatever happens
to be in str[] -- which is the last line of the input file
read in step (1).

Rewriting the loop to something like:

while (!feof(fp) && fgets(str, 120, fp) != NULL)
printf("%s", str);

makes sure that printf() will not be called on str[] when fgets()
returns NULL (i.e. because there is no more data, since you just
reached EOF).

In fact, feof() is a bit redundant here, since fgets() will
return NULL whenever it can't read more data and EOF is just
*one* of those conditions.

- Giorgos
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top