OpenBSD manual page server

Manual Page Search Parameters

STRNCPY(3) Library Functions Manual STRNCPY(3)

strncpycopy part of a string to another

#include <string.h>

char *
strncpy(char *dst, const char *src, size_t len);

The () function copies not more than len characters from the string src to dst. If src is less than len characters long, it appends ‘\0’ characters for the rest of len. If the length of src is greater than or equal to len, dst will not be NUL-terminated.

If the src and dst strings overlap, the behavior is undefined.

The strncpy() function returns dst.

The following sets chararray to “abc\0\0\0”:

(void)strncpy(chararray, "abc", 6);

The following sets chararray to “abcdef” and does not NUL terminate chararray because the length of the source string is greater than or equal to the length parameter. strncpy() NUL terminates the destination string when the length of the source string is less than the length parameter.

(void)strncpy(chararray, "abcdefgh", 6);

The following copies as many characters from input to buf as will fit and NUL terminates the result. Because strncpy() does not guarantee to NUL terminate the string itself, it must be done by hand.

char buf[BUFSIZ];

(void)strncpy(buf, input, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';

Note that strlcpy(3) is a better choice for this kind of operation. The equivalent using strlcpy(3) is simply:

(void)strlcpy(buf, input, sizeof(buf));

bcopy(3), memccpy(3), memcpy(3), memmove(3), strcat(3), strlcpy(3), strncat(3), wcscpy(3), wcslcpy(3)

The strncpy() function conforms to ANSI X3.159-1989 (“ANSI C89”).

The strncpy() function first appeared in Version 7 AT&T UNIX.

December 19, 2013 OpenBSD-5.5