我正在读取这样的文件:
31 0A 34 0A 31 0A 38 0A 34 0A 33 0A 36 0A 31 0A 31 0A 39 0A 31 30 0A 31 30 0A 35 0A 35 0A 31 30 0A 31 0A 33 0A 36 0A 33 0A 31 30 0A 35 0A 31 0A 31 30 0A 39 0A 35 0A 38 0A 33 0A 36 0A 34 0A 33 0A 36 0A 35 0A 31 30 0A 37 0A 32 0A 36 0A 33 0A 36 0A 35 0A 31 30 0A 37 0A 39 0A 33 0A 36 0A 32 0A 36 0A 35 0A 34 0A 0A 30 20 31 20 34 37 32 37 0A 30 20 33 20 36 33 36 33 0A 30 20 34 20 33 36 35 37 0A 30 20 35 20 33 31 33 30 0A 30 20 36 20 32 34 31 34 0A 30
我打算使用以下代码阅读文件的第一部分,直到找到序列 0A 0A:
readed = fscanf(f,"%s", str_aux);
在0A 0A之后我需要阅读以下句子:
readed = fscanf(f,"%s %s %s", str_aux1, str_aux3, str_aux3);
我如何检测 0A 0A 以便开始读取文件的第二部分。
我想使用以下结构:
while (something){
readed = fscanf(f,"%s", str_aux);
}
while (fscanf(f, "%s %s %s", a,b,c)!= EOF){
...
...
}
对某些情况的一些想法(在第一个 while 内)?
我在 Linux 上工作。
最佳答案
我可能会使用 fgetc 和状态引擎。像这样的东西:
int state=0;
char d;
while ((d = fgetc(f)) >= 0) {
if (d==0x0a)
state++;
else
state = 0;
if (state == 2)
do_something();
}
不过,我可能会使用 fgets。像这样的东西:
int state=0;
char line[MAXLINE];
while (fgets(line,sizeof(line),f))
if (state == 0 && *line == 0x0a)
state=1;
else if (state == 1)
{
sscanf(line,"%s %s %s",a,b,c);
do_something_else();
}
}
一般来说,我对调用 fscanf() 非常谨慎。我一直发现 fscanf 解析器非常脆弱。我更有可能通过 fgets 或其他方式获取该行,然后解析结果。
关于c - 使用 C 的 fscanf 检测 0x0a,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6171462/