C语言 在 C 中读取文件时跳过一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16107976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Skip a line while reading a file in C
提问by MarkWarriors
I have a problem and I haven't found a solution that works. It's really easy, but I don't understand what to do.
我有一个问题,我还没有找到有效的解决方案。这真的很容易,但我不明白该怎么做。
I have a file with some lines, like:
我有一个包含一些行的文件,例如:
#comment
#comment
icecream 5
pizza 10
pie 7
#comment
tortillas 5
fajitas 5
And I want that my program just read the lines that don't start with #.
我希望我的程序只读取不以#.
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");
采纳答案by Jerry Coffin
There's no real way to get to the next line without reading the line that starts with the #. About all you can do is read that data, but ignore it.
如果不阅读以#. 您所能做的就是读取该数据,但忽略它。
char ignore[1024];
fgets(ignore, sizeof(ignore), pf);
回答by MarkWarriors
If you need to read a configuration file, then use the right tool instead of reinventing the wheel.
如果您需要读取配置文件,请使用正确的工具而不是重新发明轮子。
while(!strcmp(first,"#")
is wrong. You want to filter out the lines which start witha hash sign, and notthe ones which are nothing but a hash sign.Also, while(!feof(f))is wrong. Furthermore, if you're reading line by line, why bother using fscanf()when you can take advantage of fgets()instead?
是错的。您想过滤掉以井号开头的行,而不是那些只是井号的行。还有,while(!feof(f))错了。此外,如果您正在逐行阅读,为什么要fscanf()在可以利用的情况下fgets()使用呢?
All in all, that whole huge whileloop can be simplified into something like this:
总而言之,整个巨大的while循环可以简化为这样的:
char buf[0x1000];
while (fgets(buf, sizeof(buf), pf) != NULL) {
if (buf[0] == '#') continue;
// do stuff
}
回答by dasblinkenlight
You can skip to end of line without using a buffer by applying %*[^\n]format specifier:
您可以通过应用%*[^\n]格式说明符在不使用缓冲区的情况下跳到行尾:
fscanf(pf, "%*[^\n]");
回答by Peter
You might want to use strstr to look for the "#".
您可能想使用 strstr 来查找“#”。
See description: http://en.cppreference.com/w/c/string/byte/strstr

