int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);
函式說明:最多從源串中拷貝n-1個字元到目標串中,然後再在後面加乙個0。所以如果目標串的大小為n的話,將不會溢位。
函式返回值:若成功則返回欲寫入的字串長度,若出錯則返回負值。
result1(推薦的用法)
#include
#include
int main()
;snprintf(str, sizeof(str
), "0123456789012345678");
printf("str=%s/n", str);
return 0;}
root] /root/lindatest
$ ./test
str=012345678
result2:(不推薦使用)
#include
#include
int main()
;snprintf(str, 18, "0123456789012345678");
printf("str=%s/n", str);
return 0;}
root] /root/lindatest
$ ./test
str=01234567890123456
snprintf函式返回值的測試:
#include
#include
int main()
;char str2[10] =;
int ret1=0,ret2=0;
ret1=snprintf(str1, sizeof(str1), "%s", "abc");
ret2=snprintf(str2, 4, "%s", "aaabbbccc");
printf("aaabbbccc length=%d/n", strlen("aaabbbccc"));
printf("str1=%s,ret1=%d/n", str1, ret1);
printf("str2=%s,ret2=%d/n", str2, ret2);
return 0;}
[root] /root/lindatest
$ ./test
aaabbbccc length=9
str1=abc,ret1=3
str2=aaa,ret2=9
解釋size:
#include
#include
int main()
,dst2[10] =;
char src1[10] ="aaa",src2[15] ="aaabbbcccddd";
int size=sizeof(dst1);
int ret1=0, ret2=0;
ret1=snprintf(dst1, size, "str :%s", src1);
ret2=snprintf(dst2, size, "str :%s", src2);
printf("sizeof(dst1)=%d, src1=%s, /"str :%%s/"=%s%s, dst1=%s, ret1=%d/n", sizeof(dst1), src1, "str :", src1, dst1, ret1);
printf("sizeof(dst2)=%d, src2=%s, /"str :%%s/"=%s%s, dst2=%s, ret2=%d/n", sizeof(dst2), src2, "str :", src2, dst2, ret2);
return 0;
}root] /root/lindatest
$ ./test
sizeof(dst1)=10, src1=aaa, "str :%s"=str :aaa, dst1=str :aaa, ret1=8
sizeof(dst2)=10, src2=aaabbbcccddd, "str :%s"=str :aaabbbcccddd, dst2=str :aaab, ret2=17
補充一下,snprintf的返回值是欲寫入的字串長度,而不是實際寫入的字串度。如:
char test[8];
int ret = snprintf(test,5,"1234567890");
printf("%d|%s/n",ret,test);
執行結果為:
10|1234
snprintf函式用法
int snprintf char restrict buf,size t n,const char restrict format,函式說明 最多從源串中拷貝n 1個字元到目標串中,然後再在後面加乙個0。所以如果目標串的大小為n的話,將不會溢位。函式返回值 若成功則返回欲寫入的字串長度,若出錯則返...
snprintf函式用法
int snprintf char restrict buf,size t n,const char restrict format,函式說明 最多從源串中拷貝n 1個字元到目標串中,然後再在後面加乙個0。所以如果目標串的大小為n 的話,將不會溢位。函式返回值 若成功則返回欲寫入的字串長度,若出錯則...
snprintf函式用法
int snprintf char restrict buf,size t n,const char restrict format,函式說明 最多從源串中拷貝n 1個字元到目標串中,然後再在後面加乙個0。所以如果目標串的大小為n 的話,將不會溢位。函式返回值 若成功則返回欲寫入的字串長度,若出錯則...