The following describes how to use the snprintf function in detail.
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, and a 0 character can be added to the end of the string. Therefore, if the target string is n, it will not overflow.
Function return value:If successful, the length of the string to be written is returned. If an error occurs, a negative value is returned.
Result1 (recommended)
Copy codeThe Code is 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 codeThe Code is 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 the returned values of the snprintf function:
Copy codeThe Code is 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 codeThe Code is 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, dst1 = % s, ret1 = % d/n ", sizeof (dst1), src1," str: ", src1, dst1, ret1 );
Printf ("sizeof (dst2) = % d, src2 = % s,/" str: % 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