snsprintf()

 

int snprintf(char *restrict buf, size_t n, const char * restrict   format, ...);

函数说明:最多从源串中拷贝 n1 个字符到目标串中,然后再在后面加一个 0 。所以如果目标串的大小为 n 的话,将不会溢出。

函数返回值:若成功则返回欲写入的字符串长度,若出错则返回负值。

Result1( 推荐的用法 )

#include <stdio.h>
#include <stdlib.h>

int main()
{
     char str[10]={0,};
     snprintf(str, sizeof(str ) , "0123456789012345678");
     printf("str=%s/n", str);
     return 0;
}

 

root] /root/lindatest
$ ./test
str=012345678


 

 

Result2:(不推荐使用)

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str[10]={0, };
    snprintf(str, 18, "0123456789012345678");
    printf("str=%s/n", str);
    return 0;
}

 

root] /root/lindatest
$ ./test
str=01234567890123456


 

 

snprintf函数返回值的测试:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str1[10] ={0, };
    char str2[10] ={0, };
    int ret1=0,ret2=0;
    ret1=snprintf(str1, sizeof(str1), "%s", "abc");
    ret2=snprintf(str2, 4, "%s", "aaabbbccc");
    printf("aaabbbccc length=%d/n", strlen("aaabbbccc"));
    printf("str1=%s,ret1=%d/n", str1, ret1);
    printf("str2=%s,ret2=%d/n", str2, ret2);
    return 0;
}

[root] /root/lindatest
$ ./test
aaabbbccc length=9
str1=abc,ret1=3
str2=aaa,ret2=9

 

转自http://hi.baidu.com/lindastar/blog/item/e7c08fafdceb63cc7dd92a4a.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值