c - 在 C 中读取文件并提取两行特定文本之间的行

标签 c string

我正在尝试从以下文件中提取 [HOCKEY] 和 [done with HOCKEY] 之间的文本:

sport.txt:

[HOCKEY]
a=10
b=20
c=30
d=45
[done with HOCKEY]
[SOCCER]
a=35
b=99
c=123
d=145
[done with SOCCER]

使用以下代码,我将能够检查该行是否为 [HOCKEY],但我无法记录 [HOCKEY] 和 [done with HOCKEY] 之间第一行和最后一行的位置

#include<stdio.h>
int main()
{
FILE *infile;
char start, end;
char *sport="[]";
char line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */
int line_number,i;
infile = fopen("sport.txt", "r");
printf("Opened file  for reading\n");
line_number = 0;
while (fgets(line_buffer, sizeof(line_buffer), infile)) {
    ++line_number;
    /* note that the newline is in the buffer */
    if (line_buffer=="[HOCKEY]")
    {
    start=line_buffer;
    printf("Found start %s",start);
  }
      if (line_buffer=="[done with HOCKEY]")
    end=line_buffer;

    while(start<end){
    printf("%c",start);
    start++;
    system("PAUSE");
    }
}
return 0;
}

最佳答案

  1. 第一行是[HOCKEY]之后的第一行。还有

  2. 最后一行是[done with HOCKEY]之前的最后一行。

所以你需要的是一行一行地读取文件。当您读取[HOCKEY]时,您正在接近您需要的真实数据,并开始读取并存储下一行的数据。继续此步骤,直到您读到[done with HOCKEY]并停止。

关于c - 在 C 中读取文件并提取两行特定文本之间的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21421060/

相关文章:

c - NetBSD:编译 cwm 后动态库错误

c - p = (int(*)[3])malloc(3*sizeof(*p)); 是什么意思?

python - 给定两个整数 m 和 n,其中 m >= n,如何创建一个生成器来返回所有滑动窗口?

php - 带有静态连接字符串变量的奇怪解析错误

python - 从字符串末尾删除标点符号

python - 在Python中大规模连接字符串

c - 我的 if 语句在 while 循环中不起作用。执行一次后退出循环

c - 我试图在 K&R 练习中定义字符串结束函数

创建一个以 null 结尾的字符串数组,其中大多数字符串数组是静态的

.net - F# 使用牛津逗号连接字符串