0

This is my first question here and I hope it is a sensible one. Here it goes:

I use a very simple loop to read value from a file:

int i=0;
int cmp;
FILE *file = fopen(file_name,"rb");

while (cmp = fscanf(file,"%f %f %f %f %f", &Gr[i], &dr[i], &eta[i], &tau[i], &v[i]) != EOF)
{
    printf("Prop=%0.4f %0.4f %0.4f %0.4f %0.4f\n%i\n%i\n", Gr[i], dr[i], eta[i], tau[i], v[i], EOF, cmp);
    i++;
}
printf("EOF=%i,File state=%i\n",cmp, EOF);

fclose(file)

I have been searching around the forum and man fscanf about information on return values of the function and what I found is that fscanf returns the number of successfully matched values. However while the loop is being executed, the value of cmp is equal to 1, rather than 5. The sample file that I use has only 4 lines with 5 columns, so when i=3 the while ends correctly, but when I print the value of cmp it is 0 and not -1 which is the alleged value of EOF. I am trying this simple snippet in an attempt to actually understand what is going on. The output of the attached code is:

Prop=-5.1300 1.1424 0.4855 1.4277 0.0578
EOF=-1,File state=1

Prop=-6.3712 1.0744 0.4082 1.3579 0.1188
EOF=-1,File state=1

Prop=-4.9538 1.4177 0.3038 1.1513 0.1428
EOF=-1,File state=1

Prop=-6.4335 1.6539 0.0863 1.8511 0.0741
EOF=-1,File state=1

File state=0, EOF=-1

The problem originated in a much larger code, where for some reason fscanf starts reading form the last line of the file. Any help will be much appreciated.

  • 2
    What happens if you put parentheses around the assignment to `cmp`, comparing that expression to EOF? – Scott Hunter May 04 '15 at 15:10
  • Your output formatting doesn't match your code (capitalization, presence/absense of the word `state`, etc.), calling into question whether that code produced that output. – Scott Hunter May 04 '15 at 15:12
  • 1
    1. Your parens are wrong; you're assigning a boolean to `cmp`. 2. Did you read the documentation for `fscanf`? – Ed S. May 05 '15 at 06:55
  • @Scott Hunter Sorry, this was the previous version... edited it now. – Peter Hristov May 05 '15 at 09:26
  • @Ed S. The man page for fscanf says that it '...returns the number of input items assigned. This can be fewer than provided for, or even zero, in the event of a matching failure. Zero indicates that, although there was input available, no conversions were assigned; typically this is due to an invalid input character, such as an alphabetic character for a `%d' conversion.'. I thought that means that if I am looking for 5 values when I call fscanf it will return 5. At one particular run it also returned 16??? Please let me know where I am going wrong as I am very new to the whole C environment. – Peter Hristov May 05 '15 at 09:33
  • @Scott Hunter Thank you very much, the parentheses trick did it (I also get a return value of 5 while running). Apologies for wasting your time! – Peter Hristov May 05 '15 at 09:36

0 Answers0