///************************* 之前說過, 研究一些程式庫的小函數到底如何寫的可增加你程式功力! 現在, 再來看看一個很常用, 也很好用的, strcpy(target, sourceString); 這個函數雖然好用, 但也很危險! 因為它無法查知你的 target 是否夠位置? 比較安全的是 strncpy( ); 但是使用時還是要小心! 請測試並研究程式碼: ****************************************************/////////// //strcpy.c test strncpy @CopyLeft by tsaiwn@csie.nctu.edu.tw char* mycpy(char*t, char*s) { // 與 strcpy做的事完全一樣! char*pOLD = t; // pOLD points to t[0]; // pOLD = &t[0]; while(*s) { // *s 就是 s[0] *t = *s; // 或寫 t[0] = s[0]; t++; ++s; } *t = 0; // 重要! terminate the string return pOLD; // 規定回傳原來 t 的開頭位址! } char* myNcpy(char*t, char*s, int n) { // 與 strncpy做的事完全一樣! char*pOLD; pOLD = t; // pOLD = &t[0]; while(*s) { if(n==0) return pOLD; // 若已經 n char 則不管尾巴的結束 '\0' 喔! *t = *s; // 或寫 t[0] = s[0]; t++; ++s; --n; // 最多 copy n char } *t = 0; // 重要! terminate the string return pOLD; // 規定回傳原來 t 的開頭位址! } char* myNcpy2(char*t, char*s, int n) { // 與 strncpy做的事完全一樣! char*pOLD = t; int i; for(i=0; i < n; i++) { // 最多 copy n char t[i] = s[i]; if(t[i] == 0) return pOLD; // done, 因為已經 copy 到尾巴了 } return pOLD; // 規定回傳原來 t 的開頭位址! } /////////////////////////////////////////////////////// #include #include int main( ) { int len; char x[]="0123456789"; char y[99]; strncpy(y, x+1, 0); printf("=%s== %d should be 0\n", y, strlen(y)); strcpy(y, x); printf("=%s== %d should be 10\n", y, strlen(y)); strncpy(y, x+1, 99); printf("=%s== %d should be 9\n", y, strlen(y)); strncpy(y, x+3, 4); printf("=%s== %d should be 4\n", y, strlen(y)); if(strlen(y) != 4) printf(" ? Why? WHY? WHY?\n"); y[3]=0; strncpy(y, x+3, 3); printf("=%s== %d should be 3\n", y, strlen(y)); len = 2; y[len]=0; myNcpy(y, x+3, 2); // strncpy(y, x+3, 2); printf("=%s== %d should be 2\n", y, strlen(y)); myNcpy(y, x+5, 20); //strncpy(y, x+5, 20); printf("=%s== %d should be 5\n", y, strlen(y)); mycpy(y, x); // strcpy(y, x); printf("=%s== %d should be 10\n", y, strlen(y)); mycpy(y, x+3); // strcpy(y, x+3); printf("=%s== %d should be 7\n", y, strlen(y)); printf("..Hit ENTER key... "); getchar( ); }