int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);
函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n 的话,将不会溢出。
函数返回值:若成功则返回欲写入的字符串长度,若出错则返回负值。
与snprintf的返回值不同,sprintf的返回值是成功写入的字符串长度,
Result1(推荐的用法)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[10]={0,};
snprintf(str, sizeof(str), "0123456789012345678");
printf("str=%s/n", str);
return 0;
}
root] /root/lindatest
$ ./test
str=012345678
补充一下,snprintf的返回值是欲写入的字符串长度,而不是实际写入的字符串度。如:
char test[8];
int ret = snprintf(test,5,"1234567890");
printf("%d|%s/n",ret,test);
运行结果为:
10|1234
自己总结:format是可以省略的
另外:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char str[10]={0};
int nLen=snprintf(str, sizeof(str), "nihao:%s", "0123456789012345678");
printf("str=%s\n",str);
printf("nLen=%d\n",nLen);
return 0;
}
输出结果:
str=nihao:012
nLen=25 为“nihao:0123456789012345678”的长度。
#define DLP_DEBUG(x, ...) \
do { \
char _dlp_log_msg[DLP_LOG_MAX_LOG_MSG_LEN] = ""; \
char *_dlp_log_temp = _dlp_log_msg;\
int cw = 0;\
if(global_loglevel >= x){\
cw = snprintf(_dlp_log_temp, DLP_LOG_MAX_LOG_MSG_LEN, "[%s,%s,%d]: ", __FILE__, __FUNCTION__, __LINE__);\
_dlp_log_temp += cw;\
snprintf(_dlp_log_temp, (DLP_LOG_MAX_LOG_MSG_LEN - cw), " "__VA_ARGS__);\
DLP_OutputBuffer(x, _dlp_log_msg);\
}\
} while (0)