天天看點

【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