天天看点

【C】库函数之 strncpy

目录

1. Copy characters from string

2. 源代码

3. 输出结果

1. Copy characters from string

#include <string.h>
char * strncpy ( char * destination, const char * source, size_t num );
           

Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case, destination shall not be considered a null terminated C string (reading it as such would overflow).

destination and source shall not overlap (see memmove for a safer alternative when overlapping).

上述内容是 cplusplus 对 strncpy 函数的介绍,

可以看出与 strcpy 函数不同的是,src 指向的 C 字符串复制到 des t所指向的数组中,复制的字符长度为 num。

如果 src 指向的字符串长度小于 count,那么在 dest 指向的字符串后面追加 '\0',直到满足本次复制的字符长度为 num。(ps:strcpy函数实现)

2. 源代码

#include <stdio.h>
#include <assert.h>
 
#define MAX_CP_CNT 5
 
#if 0
char *Strncpy(char *dest, const char *src, size_t n) {
    assert((NULL != src) && (NULL != dest));
 
    char *ret = dest;
 
    while (n && ((*ret++) = (*src++)))
        --n;
 
    if (n) { /* 如果还没有拷贝完 n 个字节 */
        while (--n) /* 字符串本身就有一个 '\0',所以这里先减去 1 */
            *ret++ = '\0';
    }
 
    return dest;
}
#endif

char *Strncpy(char *dest, const char *src, size_t n) {
    assert((NULL != src) && (NULL != dest));
 
    size_t i = 0;
 
    for (; (i < n) && ('\0' != src[i]); ++i)
        dest[i] = src[i];
 
    for (; i < n; ++i)
        dest[i] = '\0';
 
    return dest;
}
 
void test() {
    char str1[10] = "abc";
    char str2[] = "xyz";
 
    printf("call Strncpy before, str1: %s, str2: %s\n", str1, str2);
    printf("call Strncpy %d bytes after, str1: %s, str2: %s\n", MAX_CP_CNT, Strncpy(str1, str2, MAX_CP_CNT), str2);
}
 
int main(void) {
    test();
 
    return 0;
}
           

3. 输出结果

call Strncpy before, str1: abc, str2: xyz

call Strncpy 5 bytes after, str1: xyz, str2: xyz