我有以下 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
它不会让我得到射手的篮板。