strncpy源碼

//

//  main.cpp

//  AUTO_PRO

//

//  Created by yanzhengqing on 12-12-11.

//  Copyright (c) 2012 yanzhengqing. All rights reserved.

//


#include <iostream>

using namespace std;


/***

 *char *strncpy(dest, source, count) - copy at most n characters

 *

 *Purpose:

 *       Copies count characters from the source string to the

 *       destination.  If count is less than the length of source,

 *       NO NULL CHARACTER is put onto the end of the copied string.

 *       If count is greater than the length of sources, dest is padded

 *       with null characters to length count.

 *

 *

 *Entry:

 *       char *dest - pointer to destination

 *       char *source - source string for copy

 *       unsigned count - max number of characters to copy

 *

 *Exit:

 *       returns dest

 *

 *Exceptions:

 *

 *******************************************************************************/



/////////////////////////////////////////////////////////////////////////////////

/*說明:

  1. __cdecl C Declaration的縮寫(declaration,聲明),表示C語言默認的函數調用方法:所有參數從右到左依次入棧,這些參數由調用者清除,稱爲手動清棧。被調用函數不會要求調用者傳遞多少參數,調用者傳遞過多或者過少的參數,甚至完全不同的參數都不會產生編譯階段的錯誤。

  2. 將一個字符串從一個位置複製到另一個位置,最多複製n個字節

  3.  按照ANSI(American National Standards Institute)標準,不能對void指針進行算法操作,即不能對void指針進行如p++的操作,所以需要轉換爲具體的類型指針來操作,例如char *。(引用網友的結論)

  4.  size_t 類型定義在cstddef頭文件中,該文件是C標準庫的頭文件stddef.hC++版。它是一個與機器相關的unsigned類型,其大小足以保證存儲內存中對象的大小。

*/


char * __cdecl strncpy (

                       char * dest,

                       constchar * source,

                       size_t count

                        )

{

   char *start = dest;

    

   while (count && (*dest++ = *source++))   /* copy string */

        count--;

    

   if (count)                             /* pad out with zeroes */

       while (--count)

            *dest++ ='\0';

    

   return(start);

}



int main()

{

   char src[50] ="";

    constchar brc[50] ="blog.csdn.net/barry_yan";

   cout<<src<<endl;

   cout<<brc<<endl;

   strncpy(src,brc,strlen(brc));

   cout<<src<<endl;

   return0;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章