Daniel
Daniel

Reputation: 3

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 ((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?

Upvotes: 0

Views: 282

Answers (2)

David Gelhar
David Gelhar

Reputation: 27900

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.

Upvotes: 1

Zooba
Zooba

Reputation: 11468

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.

Upvotes: 0

Related Questions