-1

I have written the following C code to write five names to a text file and print the same on the monitor. While reading the data from the file, the last string is printed twice on the screen..But why..

#include<stdio.h>
#include<conio.h>

void main()
{
  FILE *fp1, *fp2, *fp3;
  char name[10];
  int n,c;
  clrscr();

  printf("How many names..\n");
  scanf("%d", &n);

  fp1 = fopen("source.txt", "w");

  while( n > 0 )
  {
    fflush(stdin);
    printf("Enter the name\n");
    gets(name);
    fprintf(fp1,"%s\n", name);
    n--;
  }

  fclose(fp1);
  fp1 = fopen("source.txt", "r");
  printf(" You entered the following names\n");

  while( !feof(fp1) )
  {
    fscanf(fp1, "%s", name);
    printf("%s\t", name);
  }

  getch();
}
Rohit S
  • 395
  • 4
  • 18
  • 1
    `while( !feof(fp1) ) { fscanf(fp1, "%s", name); printf("%s\t", name); }` --> `while( EOF!=fscanf(fp1, "%s", name) ) { printf("%s\t", name); }` – BLUEPIXY May 18 '15 at 16:25
  • 1
    `foef` is only set AFTER a "failed" read attempt. Full answer here: http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Amit May 18 '15 at 16:28
  • 4
    Yup - knew what this was from the title:( – Martin James May 18 '15 at 16:31
  • C does not look into the future on`FILE` input. End-of-file is not flagged until after it occurs. So check the return value of `fscanf()` instead. Also 2) do not use `gets()` use `fgets()` or `getline()` 3) do not use `fflush(stdin);` - not needed 3) check return values from `scanf()` and family. – chux - Reinstate Monica May 18 '15 at 16:53

1 Answers1

-1

Because you didn't read manual for feof.

The C version feof didn't automatically return true when you are at the end of file. It will return true after you attempt reading something only to find no more data to read.

Other language's "feof" may be a little easier to use. For example, Perl's eof will return 1 if the next read on FILEHANDLE will return end of file ...

ntysdd
  • 1,206
  • 2
  • 9
  • 19