I am writing code which very simply reads in a file and prints out what was in the file appropriately.
I have always struggled with getting such a program to terminate upon end of file and think I’ve found the appropriate solution, however each line is printing twice in my output, for a reason beyond me.
Here is my main file:
int main(int argc, char *argv[]) {
// insure 2 arguments given, one for a.out and one for the test file
if (argc != 2) {
// result if request fails
printf("Requires 2 arguments. Be sure to include test file location\n");
return 0;
}
FILE *fp; //open the file
fp = fopen(argv[1], "r");
char option;
int key;
int i = 0;
while (fscanf(fp, "%c %d", &option, &key) != EOF) {
printf("%d\n", key);
}
}
The key is printing twice!
Hopefully this is a simple error I’m just overlooking due to overexposure to the problem.
You probably want:
And you also want to check the return value of
fscanfto make sure it equals 2.In the first iteration of your loop, the newline is not being consumed.
In the second iteration, the newline is consumed and put in
option, and the%ddoes not match, andfscanfreturns 1.keyis unchanged which is why it gets printed again.In the third iteration,
fscanffinally returnsEOF.General rule: Always check return values to ensure they are what you expect. (You also violate this rule by failing to check the return from
fopen.) At worst it does nothing; at best, it helps you debug problems like this.