Trouble reading a line using fscanf()

2019-01-09 04:34发布

I'm trying to read a line using the following code:

while(fscanf(f, "%[^\n\r]s", cLine) != EOF )
{
    /* do something with cLine */
}

But somehow I get only the first line every time. Is this a bad way to read a line? What should I fix to make it work as expected?

标签: c file input std
7条回答
smile是对你的礼貌
2楼-- · 2019-01-09 05:28

If you try while( fscanf( f, "%27[^\n\r]", cLine ) == 1 ) you might have a little more luck. The three changes from your original:

  • length-limit what gets read in - I've used 27 here as an example, and unfortunately the scanf() family require the field width literally in the format string and can't use the * mechanism that the printf() can for passing the value in
  • get rid of the s in the format string - %[ is the format specifier for "all characters matching or not matching a set", and the set is terminated by a ] on its own
  • compare the return value against the number of conversions you expect to happen (and for ease of management, ensure that number is 1)

That said, you'll get the same result with less pain by using fgets() to read in as much of a line as will fit in your buffer.

查看更多
登录 后发表回答