strncpy() — Copy string
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
Format
#include <string.h>
char *strncpy(char * __restrict__string1, const char * __restrict__string2, size_t count);
General description
The strncpy() built-in function copies at most count characters of string2 to string1. If count is less than or equal to the length of string2, a NULL character (\0) is not appended to the copied string. If count is greater than the length of string2, the string1 result is padded with NULL characters (\0) up to length count.
If copying takes place between objects that overlap, the behavior is undefined.
Returned value
strncpy() returns string1.
Example
CELEBS46
/* CELEBS46
This example demonstrates the difference between &strcpy.
and &strncpy..
*/
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char source[ SIZE ] = "123456789";
char source1[ SIZE ] = "123456789";
char destination[ SIZE ] = "abcdefg";
char destination1[ SIZE ] = "abcdefg";
char * return_string;
int index = 5;
/* This is how strcpy works */
printf( "destination is originally = '%s'\n", destination );
return_string = strcpy( destination, source );
printf( "After strcpy, destination becomes '%s'\n\n", destination );
/* This is how strncpy works */
printf( "destination1 is originally = '%s'\n", destination1 );
return_string = strncpy( destination1, source1, index );
printf( "After strncpy, destination1 becomes '%s'\n", destination1 );
}
Output
destination is originally = 'abcdefg'
After strcpy, destination becomes '123456789'
destination1 is originally = 'abcdefg'
After strncpy, destination1 becomes '12345fg'