部分GNU代码片 18、字符串操作


size_t strlcat(
        register char* s, register const char* t, register size_t n)
{
    const char* o = t;
   
    if (n)
    {
        while (--n && *s)
            s++;
        if (n)
            do
            {
//                if (!--n)  //这里是http://www.google.com/codesearch?hl=zh-CN&q=+strlcat+show:KiQJipp-bKc:-XhE0e2favM:qI68VRkNHVY&sa=N&cd=4&ct=rc&cs_p=http://gentoo.osuosl.org/distfiles/ast-ksh.2006-02-14.tgz&cs_f=src/lib/libast/string/strlcat.c#first给出的代码,感觉有问题,现在更正如下
                if (!n--)
                {
                    *s = 0;
                    break;
                }
            } while (*s++ = *t++);
        else
            *s = 0;
    }

//更不大明白这一段代码是搞什么的,很郁闷,他根本就没有意义
//    if (!n)
//        while (*t++)
//            ;
//    return t - o - 1;

    //下面是返回还剩余多少字符没能cat上

    if ((unsigned int )-1 == n)
    {
        o = t;
        while (*t++)
            ;
        return t-o-1;
    }
    return 0;

//    return t-o;//这个用来返回已经cat的长度
}


#define DEBUG_ME
#define  HAVE_CLOCK_GETTIME
extern double time_cost(void);
int main()
{
   
    char zA[7]="1234";
    char zB[5]="456";
   
    char zC[1024]="";
    char zD[1000]="123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
    cout <   
    cout << strlcat(zA, zB, sizeof(zA)) <   
    cout << zA <   
#ifdef  DEBUG_ME
                double tCost = time_cost();
#endif    
               
     for(int i=0;i<10000;i++) 
     {
         strlcat(zC, zD, sizeof(zC));
         *(zC+400) = 0;
     }
   
#ifdef  DEBUG_ME
                tCost = time_cost() - tCost;
                printf("Time: %lf seconds/n", tCost);
#endif    

}

 

Time: 0.075000 seconds这是做10000次的cat的耗时。

 time_cost函数参考前文

 

你可能感兴趣的:(linux)