|STRNCPY(3)||Library Functions Manual||STRNCPY(3)|
*dst, const char
strncpy() function copies not more than len characters from the string src to the buffer dst. If src is less than len characters long, it fills the remaining buffer with ‘
\0’ characters. If the length of src is greater than or equal to len, dst will not be NUL-terminated.
strncpy() only NUL
terminates the destination string when the length of the source string is
less than the length parameter.
If the src and dst strings overlap, the behavior is undefined.
strncpy() function returns dst.
(void)strncpy(chararray, "abc", 6);
The following sets chararray to “abcdef”, without a NUL-terminator:
(void)strncpy(chararray, "abcdefgh", 6);
The following sequence copies as many characters from input to buf as will fit, and then NUL terminates the result by hand:
char buf[BUFSIZ]; (void)strncpy(buf, input, sizeof(buf) - 1); buf[sizeof(buf) - 1] = '\0';
By now it is clear that
dangerously easy to misuse. The
strlcpy(3) function is safer for this
kind of operation:
if (strlcpy(buf, input, sizeof(buf)) >= sizeof(buf)) goto toolong;
strncpy() function conforms to ANSI X3.159-1989 (“ANSI C89”).
strncpy() function first appeared in Version 7 AT&T UNIX.
|April 19, 2014||OpenBSD-current|