c - 如何读取txt文件的部分内容

标签 c strstr

我有以下篮子.txt 文件

Center
defence=45
training=95

Shooter
points=34
Rebounds=7

Shooter
points=8
Rebounds=5

Forward
points=8
Rebounds=5

我只想获取并显示射手值。要返回这样的内容:

Shooter
points=34
Rebounds=7

Shooter
points=8
Rebounds=5

我的想法是逐行读取文件,并在找到字符串射手时使用 strstr,然后打印其上方的所有内容。但是用下面的代码

int main()
{
  static const char filename[] = "basket.txt";
  FILE *file = fopen (filename, "r");
if (file!= NULL)
{
    char line[128];
    while (fgets (line, sizeof line, file)!= NULL)
    {
        char *line1 = strstr(line,"Shooter");
        if (line1)
        {
        while (fgets (line, sizeof line, file)!= NULL)
        fputs(line,stdout);
        }
    }
fclose(file);
}
else
{
    perror(filename);
}
return 0;
}

它返回我

Shooter
points=34
Rebounds=7

Shooter
points=8
Rebounds=5

Forward
points=8
Rebounds=5

那么我如何更改我的代码以获得我想要的结果?

更新

我改变了while循环

while (fgets (line, sizeof line, file)!= NULL)
    {
        char *line1 = strstr(line,"Shooter");
        if (line1)
        {
            fgets (line, sizeof line, file);
            while (line[0] != '\n')
            {
                fputs(line,stdout);
                fgets (line, sizeof line, file);
                break;
            }

但是现在结果

points=34
points=8

它不会给我返回射手队的篮板球。

最佳答案

if (line1)
{
    while (fgets (line, sizeof line, file)!= NULL)
    fputs(line,stdout);
}

这是错误的,因为 fgets() 在文件末尾之前不会返回 NULL。您想要读取直到遇到空行:

if (line1) {
    fgets(line, sizeof line, file);
    while (line[0] != '\n') {
        fputs(line, stdout);
        fgets(line, sizeof line, file);
    }
}

关于c - 如何读取txt文件的部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17547559/

相关文章:

c - 在 strstr 遇到 sigsegv 之前停止它

C strstr问题,即使应该是1却返回0?

java - 是否可以在基于 JNI 的 Java 应用程序中检测并(自动或手动)重新加载崩溃的 DLL

c - 如何获得终端窗口宽度?

自定义 memstr (strstr) 速度优化

c - 在 C 中获取子字符串

c - C中获取strstr之前和之后的文本

C数组结构

c - 使用双指针时的奇怪行为

c++ - 在排序和旋转的数组中搜索