snprintf

Part of the ANSI C99 language standard

Syntax

int snprintf (char * str, int n, const char * format, ... )

Arguments

str
Pointer to a string buffer to store the string
n
Maximum number of bytes to be written to the string buffer
format
Specifies the format of the resulting string, including types of the variables to be included in the string.
...
Additional variables to substitute for the formatting symbols in format

Return

The number of characters written, not including the terminating null character, or -1 if an error occurred.

Description

snprintf "prints" a formatted string (up to a defined length), except instead of printing it to a terminal console the result is stored in a string variable.

Comments

To prevent security problems and memory errors caused by buffer overruns, you should always use this function (snprintf) instead of sprintf. The formatting uses the printf-style formatting common to the C language.

printf Format Specifiers

%% % symbol
%c A single character
%d A signed integer in decimal format
%f A double precision floating point number in decimal format
%i A signed integer
%o An unsigned integer in octal format
%s A string
%u An unsigned integer
%x An unsigned integer in lowercase hexadecimal format
%X An unsigned integer in uppercase hexadecimal format

Example

int version = 1;
strcpy(str0, "Plug-In Name");
strcpy(str1, "Company Name");

// Note: size of str2 is 255 bytes
snprintf(str2, 255, "You are running %s made by %s, version %d", str0, str1, version);

printf(str2);

See Also

formatString, printf, sprintf