Faulty while loop

B

bildad

Why does my while loop print the last line of the file twice?
Thanks.

void ReadFile(FILE *fp)
{
char buff[MAX_LEN];

while (!feof(fp)) {
fgets(buff, MAX_LEN, fp);
printf("%s", buff);
}
}
 
B

bildad

Why does my while loop print the last line of the file twice?
Thanks.

void ReadFile(FILE *fp)
{
char buff[MAX_LEN];

while (!feof(fp)) {
fgets(buff, MAX_LEN, fp);
printf("%s", buff);
}
}

Never mind. I should have read posts before sending. Sorry.
 
J

Jordan Abel

Why does my while loop print the last line of the file twice?
Thanks.

void ReadFile(FILE *fp)
{
char buff[MAX_LEN];

while (!feof(fp)) {
fgets(buff, MAX_LEN, fp);
printf("%s", buff);
}
}

Because you're using feof() to check for an end-of-file condition at
the top of the loop. Using the return value of fgets() instead, or
(i believe) checking at the end of the loop, would both solve your
problem.
 

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,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top