0

I wrote this code and it seems there is a problem with the function fseek(). As it affects on the reading from the text file. It makes the function fscanf() reads something like garbage from the file and wrong data. My file contains just float numbers.

FILE *fptr;
if ( !( fptr = fopen( "saving.txt", "r" ))){
    printf( "File could not be opened to retrieve your data from it.\n" );
}
else {
    fseek(fptr, 0, SEEK_END);
    unsigned long len = (unsigned long)ftell(fptr);
    if (len > 0) {  //check if the file is not empty.
        while ( !feof( fptr ) ){
            fscanf( fptr,"%f\n", &p.burst_time );
            //printf("time = %f\n",p.burst_time);
            AddProcess(&l,p.burst_time);
        }
    }
    fclose( fptr );
}

Hint: This part of code to know whether the file is empty or not. If not read from it. I also use the function rewind(fptr); before the loop, but there is no difference.Thanks in advance.

  • 1
    possible duplicate of [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Barmar May 08 '15 at 23:52
  • 1
    You need to test the return value of `fscanf()` to see if it read anything. – Barmar May 08 '15 at 23:52
  • 2
    Why do you expect to be able to read anything if you first seek to the end of the file? There's nothing there! – Barmar May 08 '15 at 23:53
  • 1
    Did you forget to go back to the beginning before the loop? – Barmar May 08 '15 at 23:54
  • I also use the function rewind(fptr); before the loop, but there is no difference and it doesn't read nothing it reads but a massive number like garbage. – Hossam Atef El-Esseily May 08 '15 at 23:59
  • It probably didn't read anything. The massive number you are seeing is most likely a random value on the memory of an uninitialized variable. Try checking for the return value of `fscanf()`. – alvits May 09 '15 at 00:47
  • A better way to test if file is empty or not is to use `stat()`. – alvits May 09 '15 at 00:47

1 Answers1

0

Looking at just an excerpt of your code:

fseek(fptr, 0, SEEK_END);
unsigned long len = (unsigned long)ftell(fptr);
if (len > 0) {  //check if the file is not empty.
    while ( !feof( fptr ) ){
        fscanf( fptr,"%f\n", &p.burst_time );

For some reason you are seeking to the end of the file before you do any reads. I'm assuming that you are doing this to figure out the size of the file.

The reason that you get crazy output is that you haven't actually read anything, so feof fails to return an end of file until the first time through.

I'd suggest you resolve this by adding fseek(fptr, 0, SEEK_SET); immediately before the while statement.

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67