且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

sgetn不null终止字符串

更新时间:2023-02-06 13:02:35

因为它可以用来读取任意数据,而不只是文本。



以eg std :: istream :: read 函数,它还采用 char * 参数,但可以用于读取任意数据,包括二进制数据。你不希望它从二进制文件中读取时添加一个字符串终止符?


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]

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?