strncpy
函数 <cstring>
char * strncpy ( char * destination, const char * source, size_t num );
从字符串复制字符
将源(source )的字符复制到目标(destination)。如果在复制num个字符之前到达source C字符串的末尾
(以null字符表示),则用"0"填充目标,直到总共有num字符被写入。
如果source长度大于num, destination的末尾不会默认添加空字符。
因此,在这种情况下,destination不能被认为是一个以空字符结尾的C字符串(这样读会溢出)。
目标和源不应重叠(重叠时,请参阅
memmove中更安全的选择)。
☲ 参数
destination
指向要复制内容的目标数组的指针。
source
要复制的C字符串。
num
从源文件复制的最大字符数。
Size_t是一个无符号整型。
☉ 返回值
返回 destination 。
☣ 示例
/* strncpy example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]= "To be or not to be";
char str2[40];
char str3[40];
/* copy to sized buffer (overflow safe): */
strncpy ( str2, str1, sizeof(str2) );
/* partial copy (only 5 chars): */
strncpy ( str3, str2, 5 );
str3[5] = '\0'; /* null character manually added */
puts (str1);
puts (str2);
puts (str3);
return 0;
}
|
输出:
To be or not to be
To be or not to be
To be
🍄 另请参阅