我有以下basket.txt文件如何阅读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
那么,怎样才能改变我的代码,有我想要的结果?
UPDATE
我改变了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
结果是不退还我射击的篮板。
您在包含“射手”的第一行后打印_every line_。这个结果真的如此出乎意料吗? (提示:什么时候你的循环终止?) –
“这不是我想要的结果” - 那为什么不做你想要的?这当然正在做你正在告诉它。 –
是的,我知道。所以问题是如何更改我的代码以获得我想要的结果。 – dali1985