0

I am having trouble reading from a file that looks like this (indentation correct):

I  00400570,3
 S 00600a70,4
I  00400573,4
 M 7ff000388,4

This is what I have done:

FILE *input = fopen(trace_file,"r");

    char line_instruction;
    mem_addr memory_add; //mem_addr is typedef unsigned long int
    int size;
    int result;

    while(!feof(input)){

        fscanf(input, "%c %lx %d",&line_instruction, &memory_add, &size);

        if(line_instruction == 'I'){
            continue;
        }

        else if(line_instruction == 'S' || line_instruction == 'L'){
            ; //Add stuff
        }

        else{
            ; //Add Stuff   
        }
}

What I wanted to happen is that the letter goes to the variable "line_instructions", the hexadecimal to "memory_add" and the int at the end to "size." This is not what happens though. What would be the correct way/ better way to do this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
al512
  • 55
  • 3
  • 3
    read lines with `fgets()`, then parse each line with a combination of plain pointer (array) indexing, `strtol()`, ... – pmg Oct 19 '20 at 17:08
  • 1
    Your `scanf()` format string will need to include a comma to match the comma in the data, and you'll want a space before the initial `%c` to skip white space (including the newline left over from the previous line of data). Hence: `" %c %lx,%d"` might be appropriate. The space before `%lx` is optional (because it skips leading white space, unlike `%c`, `%[…]` scan sets, or `%n` — the only conversion speficiers that do not skip leading white space); you might add one before the comma; it depends on how systematically formatted your data is. Consider using `fgets()` and `sscanf()` too. – Jonathan Leffler Oct 19 '20 at 17:09
  • 4
    BTW: `while (!feof(file))` is always wrong ... ==> https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – pmg Oct 19 '20 at 17:09
  • Yes, drive the loop with `fscanf` result: `while(fscanf(input, "%c %lx %d", ...) == 3)` But you'll probably need a space in front of `%c` to filter the newline, so `fscanf(input, " %c %lx %d", ...)` – Weather Vane Oct 19 '20 at 17:27

0 Answers0