Skip a line while reading a file in C

2019-05-17 04:37发布

问题:

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



标签: c file-io scanf