tags:

views:

368

answers:

2

I have program like (from link text)

FILE* soubor;
char buffer[100];
soubor = fopen("file","r");
string outp = "";
while (! feof(soubor))
{
        fgets(buffer,100,soubor);
        fputs (buffer , stdout);
}
fclose(soubor);

and file like

A
B
C
D
E

and the output of program is

A
B
C
D
E
E

it repeats last line of file twice. I have this problem in other programs too.

+7  A: 

The problem is that for the last line, fgets will fail. However you aren't checking feof until the next loop, so you still call fputs which will print the contents of buffer, i.e. the previous line.

Try this:

FILE* soubor;
char buffer[100];
soubor = fopen("file","r");
string outp = "";
while (true)
{
  fgets(buffer,100,soubor);
  if (feof(soubor))
    break;
  fputs (buffer , stdout);
}
fclose(soubor);
Ben Russell
Nooooo.. Don't do this.
Martin York
The standard pattern (in all porocedural languages) is to put the get statement as the condition to the loop. If it fails the loop is never entered.
Martin York
+3  A: 

Using feof() as the condition for a loop to read from a file nearly always leads to problems. The standard way would look like this:

while (fgets(buffer, 100, infile))
    fputs(buffer, stdout);
Jerry Coffin