When/why is it a bad idea to use the fscanf() function?

前端 未结 6 997
忘掉有多难
忘掉有多难 2020-12-16 05:20

In an answer there was an interesting statement: \"It\'s almost always a bad idea to use the fscanf() function as it can leave your file pointer in an

6条回答
  •  旧巷少年郎
    2020-12-16 05:59

    The case where this comes into play is when you match character literals. Suppose you have:

    int n = fscanf(fp, "%d,%d", &i1, &i2);
    

    Consider two possible inputs "323,A424" and "323A424".

    In both cases fscanf() will return 1 and the next character read will be an 'A'. There is no way to determine if the comma was matched or not.

    That being said, this only matters if finding the actual source of the error is important. In cases where knowing there is malformed input error is enough, fscanf() is actually superior to writing custom parsing code.

提交回复
热议问题