MDGSF Software Engineer

[C/C++] strncpy 库函数实现

2016-12-12

#include <stdio.h>
#include <string.h>

char * Mystrncpy(char * pcDest, char * pcSrc, size_t count)
{
    if(NULL == pcDest || NULL == pcSrc) {
        return NULL;
    }

    char * pcStart = pcDest;

    while (count && (*pcDest++ = *pcSrc++))
    {
        count--;
    }

    if(count != 0)
    {
        while (--count != 0)
        {
            *pcDest++ = '\0';
        }
    }

    return pcStart;
}

void vTest1()
{
    char acSrc[] = "hello world";
    char acDest[128] = {0};
    Mystrncpy(acDest, acSrc, sizeof(acDest));
    if(strcmp(acDest, acSrc) != 0)
    {
        printf("vTest1 failed\n");
    }

    printf("vTest1 pass\n");
}

void vTest2()
{
    char acSrc[] = "hello world";
    char acDest[128] = {0};
    char * pcDest = Mystrncpy(acDest, acSrc, sizeof(acDest));
    if(strcmp(pcDest, acSrc) != 0)
    {
        printf("vTest2 failed\n");
    }

    printf("vTest2 pass\n");
}

int main()
{
    vTest1();
    vTest2();
    return 0;
}

weixingongzhonghao

Similar Posts

Comments