Normally, I compare the number returned by sscanf
with the number of fields described in the format string to detect a scanning-failure (full or partial):
if (sscanf(line, "%s: %d", name, &value) != 2)
errx(EX_USAGE, "cannot parse line %s", line);
However, what's one to do, when the format string itself is not known until run time (say, it is read from a config-file)?
In the below example, the format can specify up to six integers, but, if it specifies fewer, that's Ok -- as long as everything specified by the format is, actually, filled out:
int fields[6], fieldCount;
fieldCount = sscanf(line, format, fields, fields + 1, fields + 2,
fields + 3, fields + 4, fields + 5);
How can one detect, that fieldCount
does not match the format
-- that the input line is invalid in some way?
I suppose, I can count all of the %
-characters in the format
(taking care to skip the %%
-sequences), but that seems quite tedious. Is there another way?