int snprintf (char *restrict buf, size_t N, const char * restrict format, ...);
function Description: copy n-1 characters from the source string up to the target string, and then add a 0 to the back. So if the target string is n, it will not overflow.
function return Value: Returns the length of the string to be written if successful, and returns a negative value if an error occurs.
RESULT1 (Recommended usage)
Copy Code code as follows:
#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)
Copy Code code as follows:
#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 for snprintf function return value:
Copy Code code as follows:
#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
Explanation Size:
Copy Code code as follows:
#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 the snprintf is the length of the string to be written, rather than the actual string size being written. Such as:
Char Test[8];
int ret = snprintf (test,5, "1234567890");
printf ("%d|%s/n", ret,test);
The results of the operation are:
10|1234