Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > reading from a text file

Reply
Thread Tools

reading from a text file

 
 
Giorgos Keramidas
Guest
Posts: n/a
 
      11-27-2005
"googler" <(E-Mail Removed)> writes:
> 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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Reading LAST line from text file without iterating through the file? Robin Wenger Java 191 03-26-2011 06:19 PM
Reading text file with wierd file extension? Lionel Python 22 02-03-2009 10:27 PM
UnauthorizedAccessException when reading XML files (no problem when reading other file-types) blabla120@gmx.net ASP .Net 0 09-15-2006 02:08 PM
reading from text file to excel file mail2atulmehta@yahoo.com C Programming 1 04-12-2005 07:50 PM
reading the DB vs. reading a text file...performance preference? Darrel ASP .Net 3 11-11-2004 02:27 PM



Advertisments