Warm tip: This article is reproduced from serverfault.com, please click
c

How to make fscanf function skip a line?

发布于 2020-11-27 23:16:36

well While I was writing the question I found this answer

which gives the following solution to make it skip that line fscanf(config_file, "%*[^\n]\n"); It worked But I don't really understand the whole thing yet for example why there is two NEWLINE characters in the pattern what each of them represent and if there's more to know about this patterns

the reference in the answer gives a brief explanation about what this characters mean But I would like a more complete explanation,

After some searching I didn't manage to put my hands on any complete reference on this characters So if someone can provide a reference to read from or something. would be appreciated

Questioner
Mahmoud Salah
Viewed
0
KamilCuk 2020-11-28 08:05:13

How to make fscanf function skip a line?

I think you could:

void skip_nl(FILE *f) {
    char c[2];
    fscanf(f, "%1[\n]", c) == 1 || fscanf(f, "%*[^\n]%*1[\n]");
}

Note that scanning %*[^\n] will fail when there will be an empty line ("fail", as in scanf will stop scanning). So if there is an empty line, %*[^\n] will scan nothing and scanf will just return. So an empty line has to be handled specially, and fscanf return value is used to detect if the scan was succesfull or not. Note that %* discarded scanning does not increment scanf return value. So first scanf("%1[\n]" with a temporary unused buffer just "detects" (and discards) an empty line. If the line is not an empty line, then %*[^\n] scans and discards one or more non-newline characters and after that %*1[\n] discards a single newline character. If you are sure that the input will not be just a newline, then %*[^\n]%*1[\n] is fine. Tested on godbolt.

But really writing the following is really not that hard...:

for (int c; (c = getc(f)) != EOF && c != '\n'; ) {}