ccc
ccc

Reputation: 93

read from text file and put into struct

i have assembler file actually text file like that

1         # Test case 1 for assembler
2                 
3                   .text
4    test1:          lwa   $1,val1
5                    prh   $1
6    val12:          lwa   $2,val2
7                    prh   $2
         ..................

i am reading each line with fgets and keeping in char buffer which name is "linebuffer" and im reading linebuffer with sscanf.

while((fgets(linebuffer,sizeof(linebuffer),ifp)!=NULL)
{
sscanf(linebuffer,"%s%s%s%s",line[i].label,line[i].opcode,line[i].operands,line[i].comment);
......
} 

and i want keep them into struct,

struct instrucion{
char lable[8];
char opcode[4];
char opearand[15];
char comment[100];
}line[65536];

problem is some columns doesnt have anything just space and sscanf skipping spaces and reading very next string and keeping in first column. sorry i could not understand exactly but i hope somebody is understand.

for example i want like that for 3rd line;

line[2].label=NULL
line[2].opcode=".text"
line[2].opernds=NULL
line[2].comment=NULL

for 4th line;

line[3].label="test1:"
line[3].opcode="lwa"
line[3].operands="$1,val1"
line[3].comment=NULL

problem is starting with 5th line its has to be like that

line[4].label=NULL
line[4].opcode="prh"
line[4].operands="$1"
line[4].comment=NULL

buts when i run code im getting this result;

line[4].label="prh"
line[4].opcode="$1"
line[4].opernds=NULL
line[4].comment=NULL

how can i deliminate this linebuffer correctly?

Upvotes: 1

Views: 720

Answers (1)

Paza
Paza

Reputation: 131

OK, so your first problem is that fgets() does not read one line - It reads up to sizeof(linebuffer) number of bytes, you can see it's man page here: http://linux.die.net/man/3/gets

Second, say that you do have only one line in the string "linebuffer", what you would like to do is use sscanf return value to determine which tokens appear in the line (scanf functions family return the number of parameters that were read from the stream).

Third, pay attention to the fact the scanf considers only spaces and newlines as tokens separators, so it will not separate the string "$1,val1" to the two sub-strings - you will need to do it manually.

And finally, there's a string-parsing function that can maybe make you life easier- strtok_r. You can see it's man page here: http://linux.die.net/man/3/strtok_r

Amnon.

Upvotes: 1

Related Questions