Skip a line while reading a file in C

42,643

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

Solution 2

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

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

Solution 3

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

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

Share:
42,643
MarkWarriors
Author by

MarkWarriors

iOS Senior Engineer

Updated on July 30, 2022

Comments

  • MarkWarriors
    MarkWarriors almost 2 years

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