-1

I have the following program within main

fgets(buffer, 99, stdin);
while (!feof(stdin))
{
printf("PrintF : %s\n", buffer);
fgets(buffer, 99, stdin);
}
return 0;

I start a cmd window and compile, then run the program with a file argument.

file.exe < samplefile.txt

within the txt file I have the following lines

Hello this is

a sample file

by alanz2223

however the output is

PrintF : Hello this is

PrintF : a sample file

it seems to omit the "by alanz2223" line. according to the fgets() function description it reads characters from stream and stores them as a C string into str(the first parameter) until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

according to this description then a newline character was approached after "Hello this is " and the output should of ended there but it goes onto the next line and outputs "a sampe file " and then approaches a newline character but there is a next line. It seems that after the second line the program terminates as if it approached the end of the file which is not the case.

Alan
  • 1,134
  • 2
  • 13
  • 25

2 Answers2

1

Remove the useless feof, and test if fgets returns an error. "End of file while reading" is a defined return value.

A bonus is you can put the reading and writing lines in a more logical order.

Community
  • 1
  • 1
Jongware
  • 22,200
  • 8
  • 54
  • 100
1

Remember that fgets moves the file buffer to the end of the line it reads. The last line is not being printed because the function reads the last line, then moves the file buffer to the end of the line where the feof function terminates the while loop. Try adding a printf after the loop finishes:

fgets(buffer, 99, stdin);
while (!feof(stdin))
{
printf("PrintF : %s\n", buffer);
fgets(buffer, 99, stdin);
}
printf("PrintF : %s\n", buffer);
return 0;
  • That solved the problem, I did not know the fgets moved the file buffer to the end of the line. I appreciate it. – Alan Oct 05 '14 at 22:59