Int snprintf (char * restrict Buf, size_t N, const char * restrict format ,...);
Function Description: a maximum of N-1 characters can be copied from the source string to the target string, followed by 0. Therefore, if the target string is N, it will not overflow.
Function return value: If the value is successful, the length of the string to be written is returned. If an error occurs, a negative value is returned.
Result1 (recommended)
# 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 returned values 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, 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 returned value of snprintf is the length of the string to be written, rather than the degree of actually written string. For example:
Char test [8];
Int ret = snprintf (test, 5, "1234567890 ");
Printf ("% d | % s/n", RET, test );
The running result is:
10 | 1234
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/crfoxzl/archive/2008/01/23/2062139.aspx