zoukankan      html  css  js  c++  java
  • snprintf函数用法(转)

    1. #include <stdio.h>
    2. int snprintf(char *restrict buf, size_t n, const char * restrict format, ...);
    函数说明:最多从源串中拷贝n-1个字符到目标串中,然后再在后面加一个0。所以如果目标串的大小为n 的话,将不会溢出。

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

    Result1(推荐的用法)

    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. int main()
    4. {
    5. char str[10]={0,};
    6. snprintf(str, sizeof(str), "0123456789012345678");
    7. printf("str=%s/n", str);
    8. return 0;
    9. }
    10. root] /root/lindatest
    11. $ ./test
    12. str=012345678

    Result2(不推荐的用法):
     

    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. int main()
    4. {
    5. char str[10]={0, };
    6. snprintf(str, 18, "0123456789012345678");
    7. printf("str=%s/n", str);
    8. return 0;
    9. }
    10. root] /root/lindatest
    11. $ ./test
    12. str=01234567890123456

     

    snprintf函数返回值的测试:

    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. int main()
    4. {
    5. char str1[10] ={0, };
    6. char str2[10] ={0, };
    7. int ret1=0,ret2=0;
    8. ret1=snprintf(str1, sizeof(str1), "%s", "abc");
    9. ret2=snprintf(str2, 4, "%s", "aaabbbccc");
    10. printf("aaabbbccc length=%d/n", strlen("aaabbbccc"));
    11. printf("str1=%s,ret1=%d/n", str1, ret1);
    12. printf("str2=%s,ret2=%d/n", str2, ret2);
    13. return 0;
    14. }
    15. [root] /root/lindatest
    16. $ ./test
    17. aaabbbccc length=9
    18. str1=abc,ret1=3
    19. str2=aaa,ret2=9


    解释SIZE:

    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. int main()
    4. {
    5. char dst1[10] ={0, },dst2[10] ={0, };
    6. char src1[10] ="aaa",src2[15] ="aaabbbcccddd";
    7. int size=sizeof(dst1);
    8. int ret1=0, ret2=0;
    9. ret1=snprintf(dst1, size, "str :%s", src1);
    10. ret2=snprintf(dst2, size, "str :%s", src2);
    11. printf("sizeof(dst1)=%d, src1=%s, /"str :%%s/"=%s%s, dst1=%s, ret1=%d/n", sizeof(dst1), src1, "str :", src1, dst1, ret1);
    12. printf("sizeof(dst2)=%d, src2=%s, /"str :%%s/"=%s%s, dst2=%s, ret2=%d/n", sizeof(dst2), src2, "str :", src2, dst2, ret2);
    13. return 0;
    14. }
    15. root] /root/lindatest
    16. $ ./test
    17. sizeof(dst1)=10, src1=aaa, "str :%s"=str :aaa, dst1=str :aaa, ret1=8
    18. sizeof(dst2)=10, src2=aaabbbcccddd, "str :%s"=str :aaabbbcccddd, dst2=str :aaab, ret2=17
    19. 补充一下,snprintf的返回值是欲写入的字符串长度,而不是实际写入的字符串度。如:
    20. char test[8];
    21. int ret = snprintf(test,5,"1234567890");
    22. printf("%d|%s/n",ret,test);
    23. 运行结果为:
    24. 10|1234






  • 相关阅读:
    Java异常处理设计(三)
    TS 3.1
    TS 3.1
    Other
    样式
    Other
    Other
    TS 3.1
    TS 3.1
    TS 3.1
  • 原文地址:https://www.cnblogs.com/ZhangJinkun/p/4584174.html
Copyright © 2011-2022 走看看