I would like to read lines from a file (memory traces from Valgrind). Each line in the file
is either of the “I 0400d7d4,8″ or ” M 0421c7f0,4″ format (i.e. white space at beginning of the line). When the code below reads the file and steps through the file, memory addresses starting with a leading 7 are output without the 7, i.e. 7ff000398
becomes ff000398
. Leading zeroes are also omitted/skipped, but that is not an issue. However, given 7ff000398
and ff000398
are different locations (numbers), and I need to partition the address for further processing.
- The following file content reproduces the problem.
S 7ff000398,8
S 7ff000390,8
- Output:
Parsed line: # 0. Operation: S, address: ff000398, size: 8
Parsed line: # 1. Operation: S, address: ff000390, size: 8
// some logic before this
FILE * pFile;
pFile = fopen(tracefile, "r");
if (!pFile) {
fprintf(stderr, "unable to open %sn", tracefile);
exit(EXIT_FAILURE);
}
char operation_id;
unsigned address;
int size;
// Line is of format " M 0x3242,4" or "I 0x324234,4"
const char *format = " %c %16x,%d";
int i = 0;
while (fscanf(pFile, format, &operation_id, &address, &size) > 0) {
printf("Parsed line: # %d. Operation: %c, address: %16x, size: %dn", i, operation_id, address, size);
i++;
}
The output of this becomes:
Parsed line: # 0. Operation: S, address: ff000398, size: 8
Parsed line: # 1. Operation: S, address: ff000390, size: 8
I’ve tried different formats to no avail (e.g. adding 0x before. Regardless of the right approach (i.e. don’t use fscanf, etc), there must be a conceptual misunderstanding I possess about how fscanf works.
Deni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.