当前位置: C语言 -- 附录 -- strncpy_s

strncpy_s函数


概要:
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
errno_t strncpy_s(char * restrict s1,
      rsize_t s1max,
      const char * restrict s2,
      rsize_t n);

描述:

该函数从参数s2指向的数组复制不超过n个连续字符(空字符后面的字符不会被复制。)到参数s1指向的数组。如果未从参数s2指向的数组复制空字符,函数将s1[n]设置为空字符。

strncpy_s函数返回时,参数s1指向的数组中strncpy_s函数写入的终止空字符(如果有)之后的所有元素值都是未指定的。


运行约束:

参数s1和参数s2不能是空指针。参数s1max和参数n应不大于宏RSIZE_MAX。参数s1max不等于0。如果参数n不小于参数s1max,参数s1max应大于strnlen_s(s2, s1max)。复制不能发生在重叠对象之间。

在存在运行约束冲突的情况下,如果参数s1不是空指针,参数s1max大于0且不大于宏RSIZE_MAX,函数将s1[0]设置为空字符。


参数:
char * restrict s1

指向目标数组的指针,复制字符将存入该数组。

rsize_t s1max

目标数组中修改的最大字符数。

const char * restrict s2

指向源数组的指针,从该数组复制字符。

rsize_t n

最多复制的字符数。


返回值:

如果不存在运行约束冲突,函数返回0;否则函数返回非0值。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
/*安全函数strncpy_s范例*/

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <string.h>

#define LENGTH 10
#define N 6

int main(void)
{
    const char source[] = {'N', 'i', 'H', 'a', 'o','\0'};
    char destination[LENGTH];
    
    if(!(strncpy_s(destination, LENGTH, source, N)))
    {
        for(int i=0; i<N; ++i)
        {
            if(destination[i] == 0)
                puts("null character.");
            else
                printf_s("%c\n", destination[i]);
        }
    }
    
    return 0;
}


输出:

N

i

H

a

o

null character.

注:使用Visual Studio编译。


相关内容:
strncpy 从字符串中复制限定数量字符的函数。
memcpy_s 复制内存区域字符序列的安全函数。
memmove_s 移动内存区域字符序列的安全函数。
strcpy_s 复制字符串的安全函数。