warning: ignoring return value of 'int fscanf

Posted by Robert Powell on Mon 26 Oct 2009 03:02 AM — 6 posts, 42,584 views.

Australia #0

act_info.c:2562: warning: ignoring return value of 'int fscanf(FILE*, const char*, ...)', declared with attribute warn_unused_result


Ok, this is the next warning that i do not understand, could someone explain whats going on here. Google just returns hundreds of bug pages.



fscanf(fp,"%s",nameread);
USA #1
It means that you shouldn't ignore the return value of fscanf, because it can give you useful/important information. What you do with that information depends on the context in which you're reading from this file, and what an error means.
Australia #2
Ok, now i understand why its throwing the error, so how do i go about using the return value to make the compiler happy.


fscanf(fp,"%d %s %s\n",&desc,name,host);

if (desc == -1 || feof( fp ))
	break;


All of the code examples i have looked at dont seem to be doing anything different to me. This is the reference i have used http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/


Thanks for your help David, what works in C does not always work right in C++ and for noobs like myself its all a trifle confusing.
Netherlands #3
From the same page you linked:

Quote:
Return Value
On success, the function returns the number of items succesfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned.


So you will need to catch the returnvalue (like in retvalue = fscanf(...);) and test if the values are correct.

The example they give is minimal, and works if you get correct input. It will have unexpected results if the data you are reading is not formatted correctly, and it is exactly those situations which you need to handle - hence the existence of a warning.
Australia #4
Would this be closer to the mark ? sure i now this wont compile, but is that the correct way to use the return value?


ret = fscanf(fp,"%d %s %s\n",&desc,name,host);

if (ret == EOF))
	break;



HEHE posted this as Worstje did, i kind of worked it out eventually. Thanks.
Amended on Mon 26 Oct 2009 08:01 AM by Robert Powell
#5
The warnings are trying to tell you that you are ignoring the error status of those two calls, i.e. you aren't checking if they succeeded.

The best solution is to check the return values like you should be doing.