一些常用字符串操作函数的内部实现

我整理了一下常用的字符串库函数的内部实现,截自linux内核中的lib/string.c文件,绝对标准的程序,供大家参考。

memset:

    /*
     * memset - Fill a region of memory with the given value
     * @s: Pointer to the start of the area.
     * @c: The byte to fill the area with
     * @count: The size of the area.
     */
    void *memset(void *s, int c, size_t count)
    {
        char *xs = s;

        while (count--)
            *xs++ = c;
        return s;
    }

memcpy:

    /*
    * memcpy - Copy one area of memory to another
    * @dest: Where to copy to
    * @src: Where to copy from
    * @count: The size of the area.
    */
    void *memcpy(void *dest, const void *src, size_t count)
    {
    char *tmp = dest;
    const char *s = src;
    while (count--)
    *tmp++ = *s++;
    return dest;
    }

memmove:

    /*
     * memmove - Copy one area of memory to another
     * @dest: Where to copy to
     * @src: Where to copy from
     * @count: The size of the area.
     * Unlike memcpy(), memmove() copes with overlapping areas.
     */
    void *memmove(void *dest, const void *src, size_t count)
    {
        char *tmp;
        const char *s;

        if (dest <= src) {
            tmp = dest;
            s = src;
            while (count--)
                *tmp++ = *s++;
        } else {
            tmp = dest;
            tmp += count;
            s = src;
            s += count;
            while (count--)
                *--tmp = *--s;
        }
        return dest;
    }

memcmp:

    /*
     * memcmp - Compare two areas of memory
     * @cs: One area of memory
     * @ct: Another area of memory
     * @count: The size of the area.
     */
    int memcmp(const void *cs, const void *ct, size_t count)
    {
        const unsigned char *su1, *su2;
        int res = 0;

        for (su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--)
            if ((res = *su1 - *su2) != 0)
                break;
        return res;
    }

strcpy:

    /*
     * strcpy - Copy a %NUL terminated string
     * @dest: Where to copy the string to
     * @src: Where to copy the string from
     */
    char *strcpy(char *dest, const char *src)
    {
        char *tmp = dest;

        while ((*dest++ = *src++) != '