Trouble reading a line using fscanf()

It’s almost always a bad idea to use the fscanf() function as it can leave your file pointer in an unknown location on failure.

I prefer to use fgets() to get each line in and then sscanf() that. You can then continue to examine the line read in as you see fit. Something like:

#define LINESZ 1024
char buff[LINESZ];
FILE *fin = fopen ("infile.txt", "r");
if (fin != NULL) {
    while (fgets (buff, LINESZ, fin)) {
        /* Process buff here. */
    }
    fclose (fin);
}

fgets() appears to be what you’re trying to do, reading in a string until you encounter a newline character.

Leave a Comment