C: fscanf erases integer variables values?
I've got a C program that encounters errors when I enter a while loop.
I initialize a variable (fragmentcount) and write into it using fscanf and assign it a value of 4 (this works)
int fragmentCount;
if ((fscanf(fp, "%i", &fragmentCount)) == 1) {
...
}
However, when I try to access it in a while loop below, fragmentCount = 0
while 开发者_JAVA百科((fscanf(fp, "%[#]", discards)) != EOF) {
printf(fragmentCount); // <- pseudocode
}
For a brief experiment, I tried taking away the fscanf as the conditional test for the while loop, and fragmentCount was the correct value (4).
Why is this so? How can I avoid this?
How is discards
declared? It is possible that fscanf is reading more data than discards
has room for, which might overwrite the value of other variables.
Using the '%[' format without a field width is a bad idea - it leaves your program open to buffer overflow errors.
fscanf
reads a value from a file and interprets it according to the format string. The '%i' format string is unknown (perhaps you meant '%d'?) according to http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/, so you are unlikely to read the value you expect.
Apart from file FILE*
and the format string, all parameters to fscanf
are out parameters, which means the value they contain before the call to fscanf
are irrelevant and could be replaced.
精彩评论