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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.
回答2:
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.