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

本文详细介绍了snprintf函数的使用方法及注意事项,包括如何处理格式化字符串长度超过指定大小的情况,并提供了一个利用snprintf进行断言检查的实际应用示例。

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


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值