Parsing a file in C with several similar blocks

2019-09-16 03:55发布

问题:

I have a file that has the following format:

abc dca
2
aa bb
casca casss

abc dca
3
aa bb
casca casss
casca casss

abcd abcd
0

Basically it goes by blocks (in the previous example there would be 3 blocks). A particular block would be:

abc dca
2
aa bb
casca casss

In all case we would have:
First line: Always two words separated by a space.
Second line: A number

From here, we would have as many lines as the previous number, and each line would have always two words.

How can I parse a file so that for each block I can call a function passing some stuff that I calculate with what I have found in the block?

回答1:

Use a minimal state machine:

#include <stdio.h>
#include <string.h>

int main(int qrgc, char **argv)
{
char buff[111];
char one[10], two[10];
char left[10], right[10];
int num;
size_t len;
int state,rc;

state =0;

while(fgets (buff, sizeof buff, stdin)) {
        len = strlen (buff);
        while (len && buff[len-1] == '\n') buff[--len] = 0;
        switch (state) {
        case 0:
                rc = sscanf(buff, "%s %s", left, right);
                if (rc < 2) goto quit;
                state=1;
                break;
        case 1:
                rc = sscanf(buff, "%d", &num);
                if (rc < 1) goto quit;
                state=2;
                break;
        default:
                if (!len) {state = 0; continue; }
                rc = sscanf(buff, "%s %s", one, two);
                if (rc < 2) goto quit;
                break;
                }
        }
quit: ;
return 0;
}


回答2:

There are many ways to do this. The two I thought of are:

If the file is not very large, then you could read it all into a list of strings (one string for each line).

Another way is to pass create a function that takes a file handle and the previous block.

(I do not want to write dynamic arrays in C)



标签: c file parsing