C Library Function - snprintf()
C Standard Library - <stdio.h>
Description
The C library function int snprintf(char *str, size_t size, const char *format, ...) formats the variable arguments (...) according to the format and copies the formatted string to str, with a maximum of size characters to be written. Any content beyond size will be truncated.
Declaration
Here is the declaration for the snprintf() function.
int snprintf ( char * str, size_t size, const char * format, ... );
Parameters
str -- The destination string.
size -- The number of bytes to be copied.
format -- The format string.
... -- The variable arguments.
Return Value
If the length of the formatted string is less than size, the entire string is copied to str, followed by a null terminator
\0
.If the length of the formatted string is greater than or equal to size, the excess part will be truncated, and only (size-1) characters will be copied to str, followed by a null terminator
\0
. The return value is the intended length of the formatted string.
Example
The following example demonstrates the use of the snprintf() function.
#include <stdio.h>
int main()
{
char buffer[50];
char* s = "tutorialprocom";
// Read the string and store it in buffer
int j = snprintf(buffer, 6, "%s\n", s);
// Output the buffer and character count
printf("string:\n%s\ncharacter count = %d\n", buffer, j);
return 0;
}
Output:
string:
runoo
character count = 10