语法:
#include <cstring> char *strncpy( char *to, const char *from, size_t count ); namespace std { using ::strncpy; }
strncpy() 拷贝from中至多count个字符到to中。如果from中少于count个字符,余下的将被填充为字符 '\0'。返回值是结果字符串。
警告: 如果仔细阅读定义,你会发现strncpy将不会为结果字符串添加空结束符!这将会令很多人惊讶,但是它有很好的原因,来让我们看看strncpy()通常的(idiomatic)使用:、
#include <cstring> #include <cstdlib> int main(int argc, char *argv[]) { if (argc!=2) { return EXIT_FAILURE; } char buff[6]; strncpy(buff, argv[1], sizeof(buff)); // Here comes the idiomatic part, that // must not be missing from code using strncpy: if (buff[sizeof(buff)-1] != '\0') { // We have overflow. You may decide to give an error: return EXIT_FAILURE; // or to truncate your string: buff[sizeof(buff)-1]='\0'; } // but in any case, make sure that at this line // you string is NULL (zero) terminated! }
strncpy()自己的使用并不会导致安全的代码。必须正确的使用它(正如上面),否则在后面的代码,如果假设6个大小的缓冲区包含至多5个字符,将会失效,而且也许会导致安全风险(崩溃或更糟)。
另外一个一直是NULL结尾的字符串是使用 strncat:
#include <cstring> #include <cstdlib> int main(int argc, char *argv[]) { if (argc!=2) { return EXIT_FAILURE; } char buff[6] = ""; strncat(buff, argv[1], sizeof(buff)-1); }