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