0

I'm trying to create an Instruction Set Simulator that reads in assembly and executes the desired action. Each line consists of [address][instruction][input1] and possibly also [input2]

The file I'm reading looks like this:

10  MOV R1, 1
11  MOV R2, 10
12  MOV R3, 101
13  ST [R3], R1
14  ADD R1, 1
15  ADD R3, 1
16  CMP R1, R2
17  JE 19
18  JMP 13
19  MOV R2, 5
20  MOV R4, 0
21  MOV R3, 109
22  MOV R1, -1 
23  LD R5, [R3]
24  ADD R3, R1
25  ADD R4, 1
26  CMP R4, R2
27  JE 29
28  JMP 23
29  MOV R3, 120
30  ST [R3], R5

and right now I'm trying to parse each line using fscanf:

char* buf[100];
    while (fscanf(fptr,"%*s %3s %*s %*s ",buf)==1)
        printf("%s\n", buf);

The output I'm getting is this:

MOV
MOV
ST
ADD
ADD
CMP
JE
13
5
0
109
-1
[R3
R3,
R4,
R4,
29
29
30

Could someone explain what's happening and suggest a way to capture each part of the instruction?

Thank you!

BCool
  • 3
  • 2
  • What did you expect that code to do? – kaylum Feb 24 '20 at 01:23
  • `char* buf[100]` should be `char buf[100]` – kaylum Feb 24 '20 at 01:25
  • @kaylum I was trying to output just the instruction string i.e. MOV – BCool Feb 24 '20 at 01:34
  • Did you re-test with the `buf` issue fixed? – kaylum Feb 24 '20 at 01:47
  • 1
    There aren't 4 fields in each line. `scanf` is not line oriented, but is reading 4 strings at a time. Since you want to treat your input as if it is line oriented, you would be better off reading it with `fgets` – William Pursell Feb 24 '20 at 02:07
  • @kaylum yes and I get the same output – BCool Feb 24 '20 at 02:21
  • @WilliamPursell I've tried that but I still need to read and save each piece of the line into separate variables and fgets just saves it as a string – BCool Feb 24 '20 at 02:22
  • After reading a line with `fgets()`, you parse the line with `scanf()`, checking the result. In fact, with the line reading regime, you don't care what comes after the opcode (instruction string), so you can use `char opcode[10]; if (sscanf(buf, "%*d %9s", opcode) != 1) { … format error… }`. One big advantage of using `sscanf()` is that you can make multiple attempts to parse the string with different formats, whereas with direct file I/O, you really can't recover easily from changes in format. – Jonathan Leffler Feb 24 '20 at 03:19
  • Also note that trailing spaces in a format string are diabolical if a human will ever type the input. See [What is the effect of trailing white space in a `scanf()` format string?](https://stackoverflow.com/q/19499060/15168) – Jonathan Leffler Feb 24 '20 at 03:23

0 Answers0