简体   繁体   中英

Why do I get a warning of ignoring return value of ‘fscanf’ when I read numbers from a file in C?

I would like to read from a file (.txt) two columns in C. Here is the code:

#include<stdio.h>

int main(int argc, char *argv[]){

FILE *f;
int t[160], i, k=0;
double omega[160];

f = fopen("data.txt", "r");

while(!feof(f)){
               fscanf(f, "%d %lf", t, omega); 
               k++;
               }

for (i = 0; i < k; i++) printf("%d %lf\n", t[i], omega[i]);

return 0;
}

When I compile the program I get the following error message:

average.c: In function ‘main’:
average.c:14:10: warning: ignoring return value of ‘fscanf’, declared with attribute    warn_unused_result [-Wunused-result]
    fscanf(f, "%d %lf", t, omega);
          ^

How can I deal with this problem? Any help would be appreciated ! Thank you!

a

Well, by not ignoring the return value, I'd guess.

Note that fscanf() (like scanf() and sscanf() ) returns the number of successful conversions it did. This is very useful so that you can know that your variables really contain the read-in data.

If you really want to ignore the value, cast the call to (void) :

(void) fscanf(f, "%d%lf", t, omega);

However your code is strangely organized; the inner fscanf() call is not needed and should be removed and the first one has the wrong arguments.

The loop should be:

while(fscanf(f, "%d %lf", t + k, omega + k) == 2)
{
   k++; 
}

Here I use t + k as shorter way of writing &t[k] (and the same with omega ).

You should not use feof() like you do in your edited question: that's just wrong. The use of feof() is after a read has failed, to figure out if it maybe failed because the input file ended. There's no need to use it like you do, fscanf() will fail, and thus return something else than 2 , on end of file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM