sprintf()的snprintf()用法
複製內容到剪貼簿
代碼:
#include <stdio.h>
using namespace std;
int main()
{
char buf[100];
sprintf(buf, "%.*s", 4, "fluke");
printf("%s/n", buf);
memset(buf, 0, sizeof(buf));
snprintf(buf, 3, "%s", "fluke");
printf("%s/n", buf);
return 0;
}
兩種用法看看輸出就明白了:
fluk
flu
int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);
函數說明:最多從源串中拷貝n-1個字元到目標串中,然後再在後面加一個0。所以如果目標串的大小為n
的話,將不會溢出。
函數傳回值:若成功則返回欲寫入的字串長度,若出錯則返回負值。
Result1(推薦的用法)
#include
#include
int main()
{
char str[10]={0,};
snprintf(str, sizeof(str), "0123456789012345678");
printf("str=%s/n", str);
return 0;
}
root] /root/lindatest
$ ./test
str=012345678
Result2:(不推薦使用)
#include
#include
int main()
{
char str[10]={0, };
snprintf(str, 18, "0123456789012345678");
printf("str=%s/n", str);
return 0;
}
root] /root/lindatest
$ ./test
str=01234567890123456
snprintf函數傳回值的測試:
#include
#include
int main()
{
char str1[10] ={0, };
char str2[10] ={0, };
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