免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3228 | 回复: 8

好吧! 我承认我连基础都没学好! glibc 的snprintf今天才知道怎么用! [复制链接]

论坛徽章:
0
发表于 2011-01-20 17:22 |显示全部楼层
本帖最后由 zhangsuozhu 于 2011-01-21 17:55 编辑

以前看前辈用snprintf如下:
  1. len += snprintf(buf-len, buf_size - len, "xxx %s", string1);

  2. len += snprintf(buf-len, buf_size - len, "xxx %s", string2);
复制代码
所以理所当然的认为如果buf的长度如果存不下string时,将返回写入buf的长度。一直也没重视 这个函数,也没man一下怎么用。
今天,偶然一个机会,测了一下。叫我汗颜。
原来glibc 的 snprintf如果buf存不下时,返回仍是字符串的长度。。。。。。
  1. 如:
  2. char buf[2];
  3. int len = 0;
  4. len = snprintf(buf, sizeof(buf), "%s","abcdef");
复制代码
我一直以为是返回1,结果杯具了,返回的是6.....
哎~~~~面壁去了!

论坛徽章:
0
发表于 2011-01-20 17:44 |显示全部楼层
snprintf是C99新规定的库函数

论坛徽章:
0
发表于 2011-01-20 17:48 |显示全部楼层
本帖最后由 davelv 于 2011-01-20 17:53 编辑

The  functions  snprintf() and vsnprintf() do not write more than size bytes (including the trailing '\0').  If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '\0') 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.)


The glibc implementation of the functions snprintf() and vsnprintf() conforms to the C99 standard, that is, behaves as described above, since  glibc version 2.1.  Until glibc 2.0.6 they would return -1 when the output was truncated.

论坛徽章:
0
发表于 2011-01-20 19:17 |显示全部楼层
snprintf是C99新规定的库函数 用的时候 有时候会报编译警告的

论坛徽章:
0
发表于 2011-01-21 00:15 |显示全部楼层
这个函数win上和aix上的行为不一样


似乎strncpy也是这样,一个有可能返回不以'\0'为结尾的字符串,另一个是肯定返回以'\0'为结尾的字符串

论坛徽章:
323
射手座
日期:2013-08-23 12:04:38射手座
日期:2013-08-23 16:18:12未羊
日期:2013-08-30 14:33:15水瓶座
日期:2013-09-02 16:44:31摩羯座
日期:2013-09-25 09:33:52双子座
日期:2013-09-26 12:21:10金牛座
日期:2013-10-14 09:08:49申猴
日期:2013-10-16 13:09:43子鼠
日期:2013-10-17 23:23:19射手座
日期:2013-10-18 13:00:27金牛座
日期:2013-10-18 15:47:57午马
日期:2013-10-18 21:43:38
发表于 2011-01-21 08:55 |显示全部楼层
呀,我以前也理解错了{:3_184:}

论坛徽章:
0
发表于 2011-01-21 09:11 |显示全部楼层
不实用吧

论坛徽章:
0
发表于 2011-01-30 15:19 |显示全部楼层

论坛徽章:
0
发表于 2011-01-30 16:56 |显示全部楼层
好吧,我承认我到今天都不知道怎么用
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP