美文网首页
snprintf()函数使用总结

snprintf()函数使用总结

作者: EamonXia | 来源:发表于2021-01-06 21:33 被阅读0次

    函数描述

    C库函数int snprintf(char * str, size_t size, const char * format, ...)

    • step1:将可变参数...按照format格式化成字符串;
    • step2:将step1得到的字符串写到str中,写多长呢?长度为size而且size包含\0

    函数声明

    int snprintf(char *str, size_t size, const char *format, ...)
    

    函数入参

    • str -- 目标字符串。
    • size -- 拷贝字节数(Bytes),长度包含\0
    • format -- 格式化成字符串。
    • ... -- 可变参数。

    返回值

    (1) 如果格式化后的字符串长度小于 size,则会把字符串全部复制到 str 中,并给其后添加一个字符串结束符 \0;
    (2) 如果格式化后的字符串长度大于等于 size,超过 size-1 的部分会被截断,只将其中的 (size-1) 个字符复制到 str 中,并给其后添加一个字符串结束符 \0,返回值为欲写入的字符串长度

    example:

    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    void main()
    {
        char *str = (char *)malloc(20 * sizeof(char));
    
        int ret = snprintf(str, 10, "123456789");
        printf("str is [%s] and ret is [%d]\n", str, ret);
        
        int ret1 = snprintf(str, 10, "1234567890");
        printf("str is [%s] and ret1 is [%d]\n", str, ret1);
    
        int ret2 = snprintf(str, 10, "12345678901");
        printf("str is [%s] and ret2 is [%d]\n", str, ret2);
    }
    
    [root@localhost test]# gcc -Og test_snprintf.c -o proc
    [root@localhost test]# ./proc
    str is [123456789] and ret is [9]
    str is [123456789] and ret1 is [10]
    str is [123456789] and ret2 is [11]
    
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    void main()
    {
        int i = 10;
        char *str = malloc(i);
        int ret = snprintf(str, 12, "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");
        printf("str is [%s] and ret is[%d] \n", str, ret);
    }
    
    
    

    相关文章

      网友评论

          本文标题:snprintf()函数使用总结

          本文链接:https://www.haomeiwen.com/subject/wocfrktx.html