-1

So i just got an assigment from my prof to make a program that would read or write a file . And i got some problem when reading an empty file , whenever i read an empty file it would input a space character and 0.0 . So is there any way to

Handle this ?

Here is my read code

void read()
{
    n = 0  ;     
    FILE *f ;

    f = fopen("namafile.txt","r");
    if (f)
    {
        while (!feof(f))
        {
            fscanf(f,"%[^|]|%[^#]#%f\n", mhs[n].nim, mhs[n].nama, &mhs[n].x) ;
            n++ ;
        }     
    }
    else
    {
        printf("file not found\n");
    }
    fclose(f) ;

}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
triton21
  • 11
  • 1

1 Answers1

1

The EOF marker will be set after fscanf() fails, so you need a failing fscanf() in order for the loop to end. Also, you have to check if fscanf() succeeded for which you check it's return value, that said all you need is to change this

while (!feof(f))

to

while (fscanf(f,"%[^|]|%[^#]#%f\n", mhs[n].nim, mhs[n].nama, &mhs[n].x) == 3)

NOTE: Don't use identifiers like f, that's a bad habit that you can porbably justify if your IDE has no autocomplete feature, but it's hardly the case, you can name your identifier file instead to make it clear what it is.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97