fgets() not working after fscanf()

前端 未结 3 1611
误落风尘
误落风尘 2020-12-21 15:49

I am using fscanf to read in the date and then fgets to read the note. However after the first iteration, fscanf returns a value of -1.

I used GDB to debug the progr

相关标签:
3条回答
  • 2020-12-21 16:09

    It looks like fgets reads the remaining entries and then stores them all in a single string.

    Yes, '\r' is not line terminator. So when fscanf stops parsing at the first invalid character, and leaves them in the buffer, then fgets will read them until end of line. And since there are no valid line terminators in the file, that is until end of file.

    You should probably fix the file to have valid (Unix?) line endings, for example with suitable text editor which can do it. But that is another question, which has been asked before (like here), and depends on details not included in your question.

    Additionally, you need dual check for fscanf return value. Use perror only if return value is -1, otherwise error message will not be related to the error at all. If return value is >=0 but different from what you wanted, then print custom error message "invalid input syntax" or whatever (and possibly use fgets to read rest of the line out of the buffer).

    Also, to reliably mix scanf and fgets, I you need to add space in the fscanf format string, so it will read up any whitespace at the end of the line (also at the start of next line and any empty lines, so be careful if that matters), like this:

    int items_read = scanf("%d ", &intvalue);

    As stated in another answer, it's probably best to read lines with fgets only, then parse them with sscanf line-by-line.

    0 讨论(0)
  • 2020-12-21 16:15

    The string you see when running GDB really ends at the first null character:

    "\rtest\r18/04/2010\rtest2\r03/05/2010\rtest3\r05/08/2009\rtest4\r\n\000"
    

    The other data after is ignored (when using ordinary str-functions);

    0 讨论(0)
  • 2020-12-21 16:20

    Don't mix fscanf() and fgets(), since the former might leave stuff in the stream's buffer.

    For a line-oriented format, read only full lines using fgets(), then use e.g. sscanf() to parse what you've read.

    0 讨论(0)
提交回复
热议问题