Trouble reading a line using fscanf()

后端 未结 7 756
暖寄归人
暖寄归人 2020-12-01 15:40

I\'m trying to read a line using the following code:

while(fscanf(f, \"%[^\\n\\r]s\", cLine) != EOF )
{
    /* do something with cLine */
}

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 15:58

    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.

提交回复
热议问题