Crfoxzl
Links: http://blog.csdn.net/crfoxzl/article/details/2062139
int snprintf (char *restrict buf, size_t N, const char * restrict format, ...);
Function Description: Copy n-1 characters from the source string to the target string, and then add a 0to the back. So if the size of the target string is n , it will not overflow.
function return value: Returns the length of the string to be written if successful, or a negative value if an error occurs.
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: (deprecated)
#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 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
Explanation 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, ret 1);
printf ("sizeof (DST2) =%d, src2=%s,/" str:%%s/"=%s%s, dst2=%s, ret2=%d/n", sizeof (DST2), Src2, "str:", SRC2, Dst2, ret 2);
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
To add, the return value of snprintf is the length of the string to be written, not the actual string size written. Such as:
Char Test[8];
int ret = snprintf (test,5, "1234567890");
printf ("%d|%s/n", ret,test);
The result of the operation is:
10|1234
Reprint--snprintf Function usage