-1

When I run the program the last data in the file gets displayed twice.

#include<stdio.h>?//heder
#include<conio.h>//header
int main(){//main
    int cn,clas;//variable declaration
    char fn[15],ln[15],pn[10],adds[15];//variable declaration
    float mr;//variable declaration
    int i=1;//variable declaration
    FILE *fp;//file pointer declaration
    fp=fopen("student.txt","r");// opening a file

    if (fopen("student.txt","r") == NULL) {
    printf("Error: file pointer is null.");
    return 0;
  }
  while(! feof(fp) ){//here the program reads the data from file
        fscanf(fp,"%d",&cn);
      fscanf(fp,"%s",&fn);
      fscanf(fp,"%s",&ln);
      fscanf(fp,"%d",&clas);
      fscanf(fp,"%s",&adds);
      fscanf(fp,"%s",&pn);
      fscanf(fp,"%f",&mr);      

      //from here the data is printed on output string
      printf("%d",cn);printf("\n");
      printf("%s",fn);printf("\n");
      printf("%s",ln);printf("\n");
      printf("%d",clas);printf("\n");
      printf("%s",adds);printf("\n");
      printf("%s",pn);printf("\n");
      printf("%f",mr);printf("\n");
      printf("\n");
      printf("\n");                     
  }
}

the file i acessed is this this is the file that i accesed and the output that the program gives is this the last one gets repeated this is output please help me with this

Manav Dubey
  • 780
  • 11
  • 26
  • 1
    You are using `feof` incorrectly. https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – William Pursell May 29 '17 at 15:24
  • 2
    Please read: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) (and read the man page too). – Weather Vane May 29 '17 at 15:25
  • One solution could be `while(fscanf(fp,"%d%s%s%d%s%s%f", &cn, fn, ln, &clas, adds, pn, &mr) == 7) { printf ... }` Note too that I removed the `&` from in front of the arguments for `%s` format specifier. – Weather Vane May 29 '17 at 15:31

1 Answers1

0

Normally, this is only worthy of a comment, but in this case it is precisely the root cause of your problem. You are using feof incorrectly. feof does not return true until after a read has failed. So your program reads the last line, then goes to the top of the loop when feof returns false. Then the first scanf fails (and all of them fail), then the printf's are executed with the data that is still available from the previous iteration of the loop, then feof returns true and the loop is terminated. You must check the return value of each scanf and break out of the loop if any of them fail to read data. Or, better yet, avoid scanf, use fread and parse the buffer.

William Pursell
  • 204,365
  • 48
  • 270
  • 300