c: how to identify EOF when using fgets()

Alex

Diamond Member
Oct 26, 1999
6,995
0
0
hi,
sorry for kinda flooding these forums with C questions these past few days, ive made a lot of progress on my assignment and im actually understanding C better now!

anyway here's one: im using fgets() to return lines of a text file one by one, thing is when it reaches the end of the file it just keeps returning a blank line every time... it works perfectly then it just prints "\n" pretty much and does this over and over so i need to identify when it has reached EOF and not let it print anything else afterwards, know what i mean?

thanks!
 

Alex

Diamond Member
Oct 26, 1999
6,995
0
0
Originally posted by: manly
man fgets

ive obviously already done this. it just says fgets() reads a stream and stops at either a newline or EOF.

however i cant still keep calling it over and over ...
 

Alex

Diamond Member
Oct 26, 1999
6,995
0
0
hmm either way this is bizarre:

fgets stores the string in "buf"

so i did:

if(strcmp(buf, ""))
printf("EOF!\n");

and it would print EOF for every line except the last ones so i just added a '!' and it works! lol
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
if(strcmp(buf, ""))

No, no, no and no. NULL pointers and empty strings are entirely different things!

char* empty = "" ; // empty HAS A VALUE it points to an address in memory where the first character has value 0
char* nowhere = NULL ; // NULL pointer

if ( empty == NULL )
printf("this won't print!\n" ) ;

if ( nowhere == NULL )
printf("this WILL print\n" ) ;

In other words, your test should be for
if (buf == NULL )

 

Alex

Diamond Member
Oct 26, 1999
6,995
0
0
i commented out my code and tried yours and the if statement would never be met (ie buf never == NULL)

the way that i did with the !strcmp somehow works so ill just leave it !

thanks for taking the time to reply tho! :)

Originally posted by: DaveSimmons
if(strcmp(buf, ""))

No, no, no and no. NULL pointers and empty strings are entirely different things!

char* empty = "" ; // empty HAS A VALUE it points to an address in memory where the first character has value 0
char* nowhere = NULL ; // NULL pointer

if ( empty == NULL )
printf("this won't print!\n" ) ;

if ( nowhere == NULL )
printf("this WILL print\n" ) ;

In other words, your test should be for
if (buf == NULL )