LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   regarding feof() function. (https://www.linuxquestions.org/questions/linux-newbie-8/regarding-feof-function-667038/)

sureshsg 09-02-2008 04:38 AM

regarding feof() function.
 
following is my code.

#include<stdio. h>
main() {
FILE *s,*d;
char a[60];
s=fopen("temp" ,"r");
while(!feof( s)) {
fgets(a,55,s) ;
printf(" %s is the string in the temp file\n",a);
}
}

output:

$ ./a.out
hsuresh is a good boy.
is the string in the temp file
hsuresh is a good boy.
is the string in the temp file

tempfilecontents:
[vskumar@dotools files]$ cat temp
hsuresh is a good boy.

------------ --------- --------- ----

Why the contents of the file temp is getting printed twice?

camh 09-02-2008 05:39 PM

Pull the printf out of your while loop and it should work:
Code:

#include <stdio.h>
main() {
 FILE *s;
 char a[60];
 s=fopen("temp","r");
 while(!feof(s)) {
  fgets(a,55,s);
 }
 printf("%s is the string in the temp file\n",a);
}


chrism01 09-02-2008 06:43 PM

See here: http://en.wikipedia.org/wiki/Fgets
Looks like you've got a blank line after your text line. fgets stops reading at new-line character, so it'll read the blank line, but put nothing into 'a', so you'll get the same content again.

MarkByers 09-02-2008 06:59 PM

fgets returns null if a line cannot be read. You should check for this.

Code:

#include<stdio.h>
main() {
  FILE *s,*d;
  char a[60];
  s=fopen("temp" ,"r");
  while(fgets(a,55,s)) {
    printf(" %s is the string in the temp file\n",a);
  }
}


feof can only see that the end of file has been reached after you attempt to read beyond the end of the file.

From feof documentation:

Checks whether the End-of-File indicator associated with stream is set, returning a value different from zero if it is.
This indicator is generally set by a previous operation on the stream that reached the End-of-File.


All times are GMT -5. The time now is 04:48 PM.