A4Treok
A4Treok

Reputation: 17

fscanf with while loop resulting in double reads per line

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

Answers (2)

Farouq Jouti
Farouq Jouti

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

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Your format string needs to match the format of your file precisely, otherwise it's going to read wrong characters into %cs.

  • Since there are spaces at the beginning of each line, the format needs to have a space there, too
  • Since there is no space after the first number and the comma, the format must not have that space either.
  • The space after the comma may stay, because %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.

Demo on ideone.

Upvotes: 1

Related Questions