解析在C文件中有几个相似的块 [英] Parsing a file in C with several similar blocks
本文介绍了解析在C文件中有几个相似的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有以下格式的文件:
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
基本上它的推移块(在previous例如会有3块)。特定块是:
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
从这里,我们必须尽可能多的行为previous数,每行会始终两个字。
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?
推荐答案
使用一个最小的状态机:
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;
}
这篇关于解析在C文件中有几个相似的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文