Problem with fgets reading last line over and over

T

Trond Valen

Hi!

Anyone who knows what the reason might be? fgets is supposed to return
null when reading EOF. I have a test for this, so my while loop should
exit, but it doesn't ...

Trond
 
K

Karl Heinz Buchegger

Trond said:
Hi!

Anyone who knows what the reason might be? fgets is supposed to return
null when reading EOF. I have a test for this, so my while loop should
exit, but it doesn't ...

Rule #1: Post Code
 
N

Niklas Norrthon

Trond Valen said:
Hi!

Anyone who knows what the reason might be? fgets is supposed to return
null when reading EOF. I have a test for this, so my while loop should
exit, but it doesn't ...

You forgot to post any code illustrating the observed behavior, so it
is very difficult to know what the reason might be.

The following should work:

#include <stdio.h>

int main()
{
char buf[42];
char* ptr;

while ((ptr = fgets(buf, sizeof buf, stdin)) != NULL) {
/* do something with buf here */
}
return 0;
}

/Niklas Norrthon
 
N

Niklas Norrthon

Rule #3: Make sure you test eof correctly with your C++ streams
Rule #4: If you for some reason use C style I/O, make sure you test
eof correctly with your FILE objects.

/Niklas Norrthon
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top