我有以下篮子.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/