C programming snprintf stdio.h

In C programming the <stdio.h> snprintf function output the data to the specified array instead of the stream.The declaration of the function is given below.

int snprintf(char * restrict s , size_t n ,
const char * restrict format, …);

s -this array stores the outputted data.

n -The n-1 number of characters is written to the ‘s’ array and a null character at the end.If ‘n’ is 0 no data is written to ‘s’.

format -The data with the conversion specifier that is to be written to ‘s’.

-An ellipsis that consists of the variable names.

Return type
int -Returns the number of characters that would have been written had ‘n’ been sufficiently large,not counting the terminating null character,or a negative value f an encoding error occurred.

***Note ‘snprintf’ is equivalent to ‘fprintf’ except that snprintf output the data to an array rather output than to a stream.

Link : C fprintf stdio.h

Code example

size_t n = 28, age = 123, ret;

char c[28] , name[ ]=”CoreCpptutor” ;

ret=snprintf(c, n, “Name=%s Age=%d”, name , age);

printf(“ret=%d”, ret );

printf(“\n\nc contains the string \”%s\”” , c);



c contains the string “Name=CoreCpptutor   Age=123”

The ‘ret’ is the number of characters written to the ‘c’ array.

Note the null character is written to the array-the first argument- only if the return value of snprintf is non-negative and less than ‘n’-the second argument.

Code example

size_t n = 28,
date = 13 ,
year=1225 ,
ret ;

char c[28] , day[ ]=”Monday” ;

ret=snprintf(c, n, “Day=%s Date=%d year=%d” , day , date , year);

printf(“ret=%d”, ret );

printf(“\n\nc contains the string \”%s\”” , c);



c contains the string “Day=Monday date=13 year=1”

Here ‘ret’value is 30>n(28) so no null terminating character is written to ‘c’ array.

Related links

->C printf stdio.h

->C sprintf stdio.h

->C vsprintf stdio.h

->C vsnprintf stdio.h