snprintf
functionThe snprintf
function in C is defined in the stdio.h
standard library and is used to write a series of characters into a character array. The main difference between snprintf
and sprintf
is that the former takes an argument that specifies the number of characters to write to the character array, whereas the latter does not take such an argument.
The structure of the snprintf
function is a follows:
int snprintf(char * str, size_t size, const char * format, ...);
Where:
str
is the pointer to the character array to which the characters are supposed to be written tosize
is an integer which denotes the number of characters to writeformat
is a format string as defined for the printf
function...
denotes optional parameters to be replaced inside the format stringThe function snprintf
returns the number of characters that are in the format
string after the formatting is applied.
Note: Null character
\0
is not counted for thesize
argument or the return value of thesnprintf
function.
snprintf
functionThe following example copies 15 characters from the string data
to the character array arr
and prints out the data in the arr
array:
#include<stdio.h>int main() {const size_t size = 15;char arr[50];char * data = "Edpresso Shots! Are Fun!";int total_chars = snprintf(arr, size, "%s\n", data);printf("%s\nTotal Characters: %d\nCharacters Copied: %d", arr, total_chars, size);return 0;}
As seen in the above example, the format
string after format processing is applied becomes Edpresso Shots! Are Fun!\n
, which comprises of 25 characters (including the new line \n
character). Since the size
is 15
, only Edpresso Shots\n
is copied. However, according to the format
string above, Edpresso Shots!
should have been copied, not Edpresso Shots\n
.
We can take this to mean that characters initially in the format
string have a higher priority than the characters that are replaced inside the format
string later on.
Free Resources