Usage resolution of the snprintf function

  • 2020-04-02 01:23:22
  • OfStack

Int snprintf(char *restrict buf, size_t n, const char *restrict   The format,...). ;
Function description: Copy up to n-1 characters from the source string to the target string, followed by a 0. So if the target string size is n, there will be no overflow.
Return value of the function: Returns the length of the string to be written on success and a negative value on error.

Result1(recommended usage)


#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:(not recommended)

#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

Test the return value of the snprintf function:

#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

Explain the 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

In addition, the return value of snprintf is the length of the string to be written, not the degree of the string actually written. Such as:
Char test [8].
Int ret = snprintf (test, 5, "1234567890");
Printf (" % d | % s/n ", ret, test);

The running result is:
10 | 1234


Related articles: