snprintf函数用法
因为 sprintf
可能导致缓冲区溢出问题而不被推荐使用,所以推荐选择使用 snprintf
函数。sprintf
和snprintf
最主要的区别:snprintf
通过提供缓冲区的可用大小传入参数来保证缓冲区的不溢出,如果超出缓冲区大小则进行截断。
snprintf
函数的原型为:
int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);
函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n 的话,将不会溢出。
snprintf
函数的实现源码为:
// glibc-2.18/stdio-common/snprintf.c:
#include <stdarg.h>
#include <stdio.h>
#include <libioP.h>
#define __vsnprintf(s, l, f, a) _IO_vsnprintf (s, l, f, a)
/* Write formatted output into S, according to the format
string FORMAT, writing no more than MAXLEN characters. */
/* VARARGS3 */
int
__snprintf (char *s, size_t maxlen, const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = __vsnprintf (s, maxlen, format, arg);
va_end (arg);
return done;
}
snprintf函数的返回值测试:
char test[10];
int ret = snprintf(test, 5, "1234567890");
printf("%d,%s/n",ret,test);
运行结果为:
10,1234