Trouble reading a line using fscanf()

后端 未结 7 742
暖寄归人
暖寄归人 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:52

    It looks to me like you're trying to use regex operators in your fscanf string. The string [^\n\r] doesn't mean anything to fscanf, which is why your code doesn't work as expected.

    Furthermore, fscanf() doesn't return EOF if the item doesn't match. Rather, it returns an integer that indicates the number of matches--which in your case is probably zero. EOF is only returned at the end of the stream or in case of an error. So what's happening in your case is that the first call to fscanf() reads all the way to the end of the file looking for a matching string, then returns 0 to let you know that no match was found. The second call then returns EOF because the entire file has been read.

    Finally, note that the %s scanf format operator only captures to the next whitespace character, so you don't need to exclude \n or \r in any case.

    Consult the fscanf documentation for more information: http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/

提交回复
热议问题