Linux C语言经常使用库函数学习之——strncpy

strncpy函数

  • 头文件:string.hweb

  • 函数原型:char *strncpy(char *dest, const char *src, int n)
    函数功能:表示把src所指向的字符串的前n个字节复制到dest所指向的字符串数组中,并返回被复制后的dest数组

  • 参数说明svg

参数名 参数说明
char *dest 字符串要被复制到的字符数组指针
const char *src 字符串将从何处拷贝的字符串指针
int n 拷贝多少个字节,通常状况为sizeof(src) - 1
  • 应用举例:
#include <stdio.h>
#include <string.h>
int main(void) { 
    char msg1[32] = "This is a test message!";
    char msg2[32] = "This is also a test message!";
    strncpy(msg2, msg1, sizeof(msg1) - 1);
    printf("msg1 is [%s]\n", msg1);
    printf("msg2 is [%s]\n", msg2);	
	return 0;
}
  • 运行结果
msg1 is [This is a test message!]
msg2 is [This is a test message!]

注意观察上面的运行结果,本来msg2是比msg1长的,可是将msg1复制到msg2后,msg2msg1多出来的部分也不见了,这是由于strncpy在复制n字节数据到dest后会在结尾加上'\0',做为字符串的结束。函数