Reputation: 17
I'm having some trouble getting fscanf to work properly when reading a text file.
My text file is (there are [spaces] in front of every letter):
L 10,4
S 18,4
L 20,4
S 28,4
S 50,4
What I want to do is read each line and store the values into some memory. Right now, however, I just want to solve this issue I'm having when using the while loop- I'm getting two outputs per line essentially, and I can't figure out why.
Here is my code:
FILE *tFile = fopen(tracefile, "r");
int address, size;
char operation;
char comma;
printf("START \n");
while(fscanf(tFile, "%c %x %c %d", &operation, &address, &comma, &size) > 0){
printf("O: %c", operation);
printf("\n");
printf("A: %x", address);
printf("\n");
printf("C: %c", comma);
printf("\n");
printf("S: %d", size);
printf("\n");
}
printf("END \n");
fclose(tFile);
Lastly, my output is
START
O:
A: 0
C:
S: 4195731
O: L
A: 10
C: ,
S: 4
O:
A: 10
C: ,
S: 4
O: S
A: 18
C: ,
S: 4
O:
A: 18
C: ,
S: 4
O: L
A: 20
C: ,
S: 4
O:
A: 20
C: ,
S: 4
O: S
A: 28
C: ,
S: 4
O:
A: 28
C: ,
S: 4
O: S
A: 50
C: ,
S: 4
O:
A: 50
C: ,
S: 4
END
Thanks for any help.
Upvotes: 1
Views: 1782
Reputation: 1667
you should output a format similar to the one written in the file
for example you have a line written as L 10,4
then it should be formated as %c %d,%d
so try fscanf(tFile, " %c %d,%d", &operation, &address, &size)
instead , unless you need the comma then you'll have to use fscanf(tFile , " %c %d%c%d" , &operation , &address , &comma , &size)
the spaces are important
Upvotes: 0
Reputation: 726579
Your format string needs to match the format of your file precisely, otherwise it's going to read wrong characters into %c
s.
%d
allows leading spaces, but it wouldn't hurt to remove that space either.This should fix the problem:
while(fscanf(tFile, " %c %x%c%d", &operation, &address, &comma, &size) > 0) ...
Note: %x
expects a pointer to an unsigned int, so you should change the declaration of address
to match the expected type.
Upvotes: 1