Link to home
Start Free TrialLog in
Avatar of prabhut
prabhut

asked on

fgets

I have written a small program to read a file line by line and to display it(as soon as it is read). The program flow is like this, I will open a file, until EOF I will read the file into a buffer of size 100 and print the buffer. At the EOF, I will close the file and exit. I am reading a text file whose content is just first,second, third, fourth and fifth(each in a separate line). When I ran the program, I got six lines printed, why so???.

     Here is the sample output :

1. first
2. second
3. third
4. fourth
5. fifth
6.

Avatar of pagladasu
pagladasu

Could you post your code.
Perhaps while creating the file, you had pressed the enter key after the last line before saving it.
Avatar of prabhut

ASKER

Here is my sample program :

#include <stdio.h>

main()
{
  FILE *fp;
  int i=1;
  char buf[100];

  fp = fopen("./file.txt","r");

  while ( !feof(fp) ) {
     fgets(buf,sizeof(buf), fp);
     printf("%d:%s\n",i,buf);
     i++;
     memset(buf,'\0',sizeof(buf));
  }

  fclose(fp);
}


Content of file.txt :

first
second
third
fourth
fifth
Avatar of ozo
while( fgets(buf,sizeof(buf), fp), !feof(fp) ){
          printf("%d:%s\n",i,buf);
          i++;
          memset(buf,'\0',sizeof(buf));
 }
ozo, I am slow
Avatar of prabhut

ASKER

I have implemented and found it is working fine. I have doubt, why it is not working in my code. I need a detail answer, please.
the 5th fgets stops at the last character in the file,
the 6th fgets detects an end of file, and reads nothing, which you print,
then you test the end of file condition and stop.
but fgets(buf,sizeof(buf), fp), !feof(fp) isn't really the best way to do this,
since it will miss a last line that's not terminated with a new-line character.
I'd instead do
while( fgets(buf,sizeof(buf), fp) ){ ... }
well done ozo.
As usual :-)
ASKER CERTIFIED SOLUTION
Avatar of cpa802
cpa802

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial