Reputation: 13738
I have a table like this;
01 01 02 00 01 02 00 01
01 02 00 01 02 00 01 02
02 00 11 04 04 04 04 04
00 01 10 03 03 03 03 03
I am reading this file like this:
FILE *map = open_file("lazy.map");
if (map == 0)
return 0;
for (i = 0; i < TOTAL_TILES; ++i) {
int ttype;
fscanf(map,"%i",&ttype);
// do other stuff here...
}
Is there a way that I can check if fscanf failed or not?
Upvotes: 0
Views: 5233
Reputation: 136238
Check the return value.
Another option is to use %n
format:
int n = -1;
int ttype;
fscanf(map, "%i%n", &ttype, &n);
if(-1 == n)
// failed to parse
This way you can check how many symbols have been consumed by fscanf
. It doesn't make difference in the above, but in:
int count = fscanf(map, "%i abc %n", &ttype, &n);
count
may be greater than one even if abc
part of the format didn't match. On the other hand, n
will be set only if the whole format matched.
Upvotes: 2
Reputation: 183270
Yes: you can examine its return-value. Per http://pubs.opengroup.org/onlinepubs/007904975/functions/scanf.html:
Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned, and errno shall be set to indicate the error.
(That page marks that last part, "and errno shall be set to indicate the error", as being POSIX-specific, meaning that the C standard itself doesn't require that errno be set; but the rest of it is all required by the C standard.)
Upvotes: 1
Reputation: 137312
Yes. From C++ reference:
Return Value
On success, the function returns the number of items successfully 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.
Upvotes: 0