Lyn
Lyn

Reputation: 729

Is trailing newline necessary in fgets?

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?

Upvotes: 2

Views: 274

Answers (2)

unwind
unwind

Reputation: 399723

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.

Upvotes: 2

4rlekin
4rlekin

Reputation: 758

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.

Upvotes: 3

Related Questions