By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,433 Members | 1,702 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,433 IT Pros & Developers. It's quick & easy.

Faulty while loop

P: n/a
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);
}
}
Nov 15 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Sat, 29 Oct 2005 02:36:40 GMT, bildad wrote:
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.
Nov 15 '05 #2

P: n/a
On 2005-10-29, bildad <bi****@wi.rr.com> wrote:
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.
Nov 15 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.