C programming vsnprintf stdio.h


int vsnprintf(char * restrict s , size_t n ,
 const char * restrict format ,
 va_list arg);

Parameters:
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’.

arg -A va_list macro consisting 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 if an encoding error occurred.Thus,the null-terminated output has been completely written if and only if the returned value is non negative and less than n.

In C programming the <stdio.h> vsnprintf function is equivalent to snprintf function but instead of using ellipsis as the second argument it is replaced by va_list macro (found in <stdarg.h> header ).A code example is given below.

Link : C vsnprintf stdio.h

Code example

void func(char *s , int n , char *format , …)
{
int ret;

va_list arg ;

va_start(arg , format);

ret=vsnprintf( s , n , format , arg);

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

va_end( arg );
}

int main( )
{
char s[30] , name[ ]=”New”;

int n = 25 , ret ;

func(s , n , “Name=%s Age=%d” , name , n);

printf(“\ns=’%s'”, s);

getchar( );
return 0 ;
}

Output,

ret=15
s=’Name=New Age=25′

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

**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.As an example in the above program change the value of ‘n’ to 10 and run the program.You will get the output as.

ret=15
s=’Name=New Age’

Here ret<n so ‘\n’ is not written to the ‘s’ string.