摘自man文檔: The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be
null-terminated.
爲了確保dest以'\0'結尾, 通常要寫成:
dest[sizeof(dest) - 1] = '\0';
strncpy(dest, src, sizeof(dest) - 1);
snprintf()會確保以'\0'結尾, 不須要設置dest末尾的'\0', 通常寫成:
snprintf(dest, sizeof(dest), ...)
strlen(dest)的最大長度爲sizeof(dest) - 1.
摘自man文檔:
The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')). If the output was truncated due to this limit then the return
value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available. Thus, a return value of
size or more means that the output was truncated. (See also below under NOTES.)
例如:
char str[64] = { 0 };
snprintf(str, 3, "abc");
printf("%s\n", str);
結果: ab
一直以來, 將snprintf像strncpy同樣用了, 才發現不用那麼費事...
還有strncat(), 不須要設置dest末尾的'\0', 但須要n + 1的空間.
摘自man文檔:
If src contains n or more characters, strncat() writes n+1 characters to dest (n from src plus the terminating null byte). Therefore, the size of dest must be at least strlen(dest)+n+1.