Is trailing newline necessary in fgets?

2019-07-15 10:59发布

When I search using keywords of 'fgets' and 'newline', there are many posts regarding how to remove the trailing newline character (and such removal appears to be a burden). Yet it seems there is few explaination on how that newline is necessary for fgets to include. Also in C++, the 'std::getline' and 'std::istream:getline' methods will not keep the newline character. So is there a reason for it?

标签: c newline fgets
2条回答
女痞
2楼-- · 2019-07-15 11:28

Here is satisfying (IMHO) explanation:
http://www.cplusplus.com/reference/cstdio/fgets/

Especially:

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

查看更多
\"骚年 ilove
3楼-- · 2019-07-15 11:28

No, it's not necessary but if present it will be included in the returned line.

The manual page says:

Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

So that's why it behaves that way.

Note that you can't assume that there will be a newline last in the buffer, you must check before removing it otherwise you risk truncating the last line if it didn't have a newline.

查看更多
登录 后发表回答