fgets() not working after fscanf()

坚强是说给别人听的谎言 提交于 2019-11-29 16:02:37
hyde

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.

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!