gpt4 book ai didi

c - 在 C 中读取文件时跳过一行

转载 作者:太空狗 更新时间:2023-10-29 15:49:00 24 4
gpt4 key购买 nike

我有一个问题,但我还没有找到有效的解决方案。这真的很容易,但我不知道该怎么做。

我有一个包含几行的文件,例如:

#comment

#comment

icecream 5

pizza 10

pie 7

#comment

tortillas 5
fajitas 5

我希望我的程序只读取不以 # 开头的行。

FILE *pf;
char first [20], second [20];
pf = fopen("config.conf", "r");
if (pf)
{
while (! feof(pf))
{
fscanf(pf, "%s \t ", first);
while(!strcmp(first,"#")){ `HERE I NEED JUMP TO NEXT LINE`
fscanf(pf, "%s \t ", first);
}
fscanf (pf, "%s \t ", second);
printf("Food: %s \t Cost: %s \n", first, second);
}
fclose(pf);
}
else
printf( "Errore nell'aprire config.conf\n");

最佳答案

如果需要读取配置文件,那么use the right tool instead of reinventing the wheel.


while(!strcmp(first,"#")

错了。您想要过滤掉井号开头的行,以及不是只是井号的行。此外,while(!feof(f)) 是错误的。此外,如果您是逐行阅读,既然可以利用 fgets(),为什么还要费心使用 fscanf()

总而言之,整个巨大的 while 循环可以简化为如下所示:

char buf[0x1000];
while (fgets(buf, sizeof(buf), pf) != NULL) {
if (buf[0] == '#') continue;

// do stuff
}

关于c - 在 C 中读取文件时跳过一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16107976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com