strncpy ()- 复制字符串
格式
#include <string.h>
char *strncpy(char *string1, const char *string2, size_t count);语言级别
ANSI
线程安全
是
描述
strncpy() 函数将 string2 的 count 个字符复制到 string1。 如果 count 小于或等于 string2的长度,那么 不会 向复制的字符串追加空字符 (\0)。 如果 count 大于 string2的长度,那么将使用空字符 (\0) 填充 string1 结果,最大长度为 count。
返回值
strncpy() 函数返回指向 string1的指针。
示例
此示例演示
strcpy() 与 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 should be similar to: *****************
destination is originally = 'abcdefg'
After strcpy, destination becomes '123456789'
destination1 is originally = 'abcdefg'
After strncpy, destination1 becomes '12345fg'
*/