Definition | #include <string.h> char *strncpy(char *s1, const char *s2, size_t n);
If string s2 contains fewer than n characters, only the length of s2 ( If string s2 contains n or more characters (excluding the null byte), string s1 is not automatically terminated with the null byte. If string s1 contains more than n characters and the last character copied from s2 is not the null byte, any data which may still remain in s1 is retained. |
Return val. | Pointer to the result string s1.
|
Notes |
Since The behavior is undefined if memory areas overlap. |
Example 1 | The following program fragment copies the entire string s2 to string s1 (like the #include <stdio.h>
#include <string.h>
int main(void)
{
int n;
char s1[20];
char s2[20];
printf("Please enter s2 (max. 19 characters)\n");
scanf("%s", s2);
printf("s1: %s\n", strncpy(s1, s2, (strlen(s2) + 1)));
return 0;
}
|
Example 2 | This program copies only a segment (8 characters) of s2 to s1. The result string is explicitly terminated with the null byte. #include <stdio.h>
#include <string.h>
int main(void)
{
char *s1 = " ";
char *s2 = "Peter is going swimming !";
strncpy(s1, s2, 8);
*(s1 + 8) = '\0';
printf("s1: %s\n", s1); /* Contents of s1: "Peter is" */
return 0;
}
|
Example 3 | In this example, only a segment (5 characters) of s2 is copied to s1. The remaining data in s1 is retained. #include <stdio.h>
#include <string.h>
int main(void)
{
char *s1 = "James is going shopping !";
char *s2 = "Peter is going swimming !";
strncpy(s1, s2, 5);
printf("s1: %s\n", s1); /* Contents of s1: "Peter is going
shopping !" */
return 0;
}
|
See also | strcpy, strlen |