Skip a line while reading a file in C

妖精的绣舞 提交于 2020-01-13 10:37:50

问题


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");

回答1:


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);



回答2:


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 with a hash sign, and not the 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?

All in all, that whole huge while loop can be simplified into something like this:

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

    // do stuff
}



回答3:


You can skip to end of line without using a buffer by applying %*[^\n] format specifier:

fscanf(pf, "%*[^\n]");



回答4:


You might want to use strstr to look for the "#".

See description: http://en.cppreference.com/w/c/string/byte/strstr



来源:https://stackoverflow.com/questions/16107976/skip-a-line-while-reading-a-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!