利用snprintf和assert向字符串流输出信息

来源:互联网 发布:网络优化外泄最低范围 编辑:程序博客网 时间:2024/05/16 19:05

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!")


0 0
原创粉丝点击