snprintf() — Print Formatted Data to Buffer
Format
#include <stdio.h>
int snprintf(char *buffer, size_t n, const char *format-string,
argument-list);
Language Level
ANSI
Threadsafe
Yes
Locale Sensitive
The behavior of this function might be affected by the LC_CTYPE and LC_NUMERIC categories of the current locale. The behavior might also be affected by the LC_UNI_CTYPE category of the current locale if LOCALETYPE(*LOCALEUCS2) or LOCALETYPE(*LOCALEUTF) is specified on the compilation command. For more information, see Understanding CCSIDs and Locales.
Description
The snprintf()
function
formats and stores a series of characters and values in the array buffer.
Any argument-list is converted and put out according to the
corresponding format specification in the format-string. The snprintf()
function
is identical to the sprintf()
function with the addition
of the n argument, which indicates the maximum number of characters
(including the ending null character) to be written to buffer.
The format-string consists of ordinary characters
and has the same form and function as the format string for the printf()
function.
Return Value
The snprintf()
function
returns the number of bytes that are written in the array, not counting
the ending null character.
Example
This example uses snprintf()
to
format and print various data.
#include <stdio.h>
char buffer[200];
int i, j;
double fp;
char *s = "baltimore";
char c;
int main(void)
{
c = 'l';
i = 35;
fp = 1.7320508;
/* Format and print various data */
j = snprintf(buffer, 6, "%s\n", s);
j += snprintf(buffer+j, 6, "%c\n", c);
j += snprintf(buffer+j, 6, "%d\n", i);
j += snprintf(buffer+j, 6, "%f\n", fp);
printf("string:\n%s\ncharacter count = %d\n", buffer, j);
}
/********************* Output should be similar to: *************
string:
baltil
35
1.732
character count = 15 */