如何阅读部分文本文件

时间:2013-07-09 11:52:54

标签: c strstr

我有以下basket.txt文件

Center
defence=45
training=95

Shooter
points=34
Rebounds=7

Shooter
points=8
Rebounds=5

Forward
points=8
Rebounds=5

我想获得并仅显示Shooter值。要返回这样的内容:

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

它没有让我回到射手的篮板。

2 个答案:

答案 0 :(得分:3)

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);
    }
}

答案 1 :(得分:0)

您的内部循环找到第一个Shooter,然后打印文件的其余部分。

内环必须停在第一个空白行。类似的东西:

while ( line[0] != '\n' )
{
    fputs...
    if ( fgets(...) == NULL )
        break;
}

这在EOF条件下表现良好。