man snprintf
int snprintf(char *str, size_t size, const char *format, ...);RETURN VALUE
Upon successful return, these functions return the number of characters printed (excluding the null byte
used to end output to strings).
The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null
byte ('\0')). If the output was truncated due to this limit, then the return value is the number of charac‐
ters (excluding the terminating null byte) which would have been written to the final string if enough space
had been available. Thus, a return value of size or more means that the output was truncated. (See also
below under NOTES.)
If an output error is encountered, a negative value is returned.
将可变个参数(...)按照format格式化成字符串,然后将其复制到str中
(1) 如果格式化后的字符串长度 < size,则将此字符串全部复制到str中,并给其后添加一个字符串结束符('\0');
(2) 如果格式化后的字符串长度 >= size,则只将其中的(size-1)个字符复制到str中,并给其后添加一个字符串结束符('\0'),返回值为欲写入的字符串长度。
可以利用这点结合自定义的调试assert进行输出
#define Assert(cond, ...) \
do { \
if(!(cond)) { \
fflush(stdout); \
fprintf(stderr, "\33[1;31m"); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\33[0m\n"); \
assert(cond); \
} \
} while(0)
#define print_asm(...) Assert(snprintf(assembly, 80, __VA_ARGS__) < 80, "buffer overflow!")
本文详细介绍了snprintf函数的使用方法及注意事项,包括如何处理格式化字符串长度超过指定大小的情况,并提供了一个利用snprintf进行断言检查的实际应用示例。
383

被折叠的 条评论
为什么被折叠?



