c - 使用 C 的 fscanf 检测 0x0a

标签 c scanf

我正在读取这样的文件:

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/

相关文章:

c - Scanf_s 读取错误的输入

c - 在循环中对带空格的字符串使用 scanf 时的有趣行为

c - TCP 非阻塞连接失败,getsockopt OptValue 113 请建议

c - (函数)交换c中的两个数字

c - fscanf 正在以某种方式更改节点(在 c 中)

c++ - 为什么 fscanf 在读取字符时失败?

c - C中的结构定义

c - 用C语言开发网络层协议(protocol)

c - 如何从C语言的natvis表达式中引用变量本身?

比较使用 fgets 和 fscanf 获取的字符串