snprintf函式用法

2021-06-23 06:47:13 字數 681 閱讀 5890

int snprintf(char *restrict buf, size_t n, const char * restrict  format, ...);

函式說明:最多從源串中拷貝n-1個字元到目標串中,然後再在後面加乙個0。所以如果目標串的大小為n 的話,將不會溢位。

函式返回值:若成功則返回欲寫入的字串長度,若出錯則返回負值。

#include

#include

int main()

;snprintf(str, sizeof(str), "0123456789101112");

printf("str=%s/n", str);

return 0;}

執行結果為:

str=012345678

snprintf的返回值是欲寫入的字串長度,而不是實際寫入的字串度。如:

char test[8];

int ret = snprintf(test,5,"1234567890");

printf("ret=%d,test=%s/n",ret,test);

執行結果為:

ret=10,test=1234

另外還有:

int pid =getpid();

snprintf(buf, sizeof(buf), "/proc/%d/cmdline", pid )

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 的話,將不會溢位。函式返回值 若成功則返回欲寫入的字串長度,若出錯則...