Sprintf () snprintf () Usage
Copy content to clipboard
Code:
#include <stdio.h>
using namespace std;
int main()
{
char buf[100];
sprintf(buf, "%.*s", 4, "fluke");
printf("%s/n", buf);
memset(buf, 0, sizeof(buf));
snprintf(buf, 3, "%s", "fluke");
printf("%s/n", buf);
return 0;
}
You can see the output in two ways:
Fluk
Flu
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
# Include
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
# Include
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
# Include
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