The *scanf
family of functions do not allow you to do that natively. Of course, you can workaround the problem by reading in the minimum number of elements that you know will be present per input line, validate the return value of *scanf
and then proceed incrementally, one item at a time, each time checking the return value for success/failure.
if (1 == fscanf(stream, "%d", &x) && (x == 'desired_value)) {
/* we need to read in some more : separated numbers */
while (2 == fscanf(stream, "%d:%d", &y, &z)) { /* loop till we fail */
printf("read: %d %d\n", y, z);
} /* note we do not handle the case where only one of y and z is present */
}
Your best bet to handle this is to read in a line using fgets
and then parse the line yourself using sscanf
.
if (NULL != fgets(stream, line, MAX_BUF_LEN)) { /* read line */
int nitems = tokenize(buf, tokens); /* parse */
}
...
size_t tokenize(const char *buf, char **tokens) {
size_t idx = 0;
while (buf[ idx ] != '\0') {
/* parse an int */
...
}
}