guanjt的个人空间 https://blog.eetop.cn/1228512 [收藏] [复制] [分享] [RSS]

空间首页 动态 记录 日志 相册 主题 分享 留言板 个人资料

日志

snprintf

已有 797 次阅读| 2016-9-23 17:17 |系统分类:芯片设计

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

函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个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


解释SIZE:

 #include <stdio.h>
#include <stdlib.h>
int main()
{
char dst1[10] ={0, },dst2[10] ={0, };
char src1[10] ="aaa",src2[15] ="aaabbbcccddd";
int size=sizeof(dst1);
int ret1=0, ret2=0;
ret1=snprintf(dst1, size, "str :%s", src1);
ret2=snprintf(dst2, size, "str :%s", src2);
printf("sizeof(dst1)=%d, src1=%s, /"str :%%s/"=%s%s, dst1=%s, ret1=%d/n", sizeof(dst1), src1, "str :", src1, dst1, ret1);
printf("sizeof(dst2)=%d, src2=%s, /"str :%%s/"=%s%s, dst2=%s, ret2=%d/n", sizeof(dst2), src2, "str :", src2, dst2, ret2);
return 0;
}
root] /root/lindatest
$ ./test 
sizeof(dst1)=10, src1=aaa, "str :%s"=str :aaa, dst1=str :aaa, ret1=8
sizeof(dst2)=10, src2=aaabbbcccddd, "str :%s"=str :aaabbbcccddd, dst2=str :aaab, ret2=17

补充一下,snprintf的返回值是欲写入的字符串长度,而不是实际写入的字符串度。如:
char test[8];
int ret = snprintf(test,5,"1234567890");
printf("%d|%s/n",ret,test);

运行结果为:
10|1234

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/crfoxzl/archive/2008/01/23/2062139.aspx


点赞

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 注册

  • 关注TA
  • 加好友
  • 联系TA
  • 0

    周排名
  • 0

    月排名
  • 0

    总排名
  • 0

    关注
  • 1

    粉丝
  • 0

    好友
  • 0

    获赞
  • 0

    评论
  • 182

    访问数
关闭

站长推荐 上一条 /1 下一条

小黑屋| 关于我们| 联系我们| 在线咨询| 隐私声明| EETOP 创芯网
( 京ICP备:10050787号 京公网安备:11010502037710 )

GMT+8, 2024-4-28 15:30 , Processed in 0.016342 second(s), 7 queries , Gzip On, Redis On.

eetop公众号 创芯大讲堂 创芯人才网
返回顶部