sgetn Doesn't Null Terminate String

2019-07-09 05:15发布

问题:

sgetn Takes a char* for it's first argument and writes characters to it. It does not write a trailing '\0' to the char*.

This behavior seems to be inconsistent with every other time that I can find a char* written to. However, it is consistent across Clang, gcc, and Visual Studio, so I can't believe it's a bug that all the compilers have.

Is there a reason that the standard doesn't require the trailing '\0' to the char*?

[Live Example]

回答1:

Because it can be used to read arbitrary data, not just text.

Take e.g. the std::istream::read function, it also takes a char* argument, but can be used to read arbitrary data, including binary data. You would not expect it to add a string terminator when reading from a binary file?