vsnprintf()

Formats a character string.

  #include <stdarg.h>
  
  #include <stdio.h>
  
  int vsnprintf(char * s, size_t n, const char * format, va_list arg);    
Parameter

s

A pointer to a character string in which to store the formatted text.

n

Maximum number of characters to store in s.

format

A pointer to a format string.

arg

An argument list.

Remarks

The vsnprintf() function works identically to snprintf(), except that the variable list of arguments that can be passed to snprintf() is replaced by an array arg of type va_list, which must have been initialized by the va_start() macro from the stdarg.h header file. The vsnprintf() does not invoke the va_end macro. If n is zero nothing is written; otherwise, any characters beyond the n-1st are discarded rather than being written to the array and a null character is appended at the end.

Vsnprintf() returns the number of characters that would have been assigned to s, had n been sufficiently large, not including the null character or a negative value if an encoding error occurred. Thus, the null-terminated output will have been completely written if and only if the returned value is nonnegative and less than n.

This facility may not be available on configurations of the EWL that run on platforms without file systems.

Listing: Example Of vsnprintf() Usage

#include <stdarg.h>

#include <stdio.h>

int sp(char *, size_t, char *, ...);

int main()

{

int i = 1;

static char s[] = "Isabelle";

char dest[50];

int retval;

retval = sp(dest, 5, "%s is number %d!", s, i);

printf("n too small, dest = |%s|, retval = %i\n", dest, retval);

retval = sp(dest, retval, "%s is number %d!", s, i);

printf("n right size, dest = |%s|, retval = %i\n", dest,

retval);

return 0;

}

// sp() formats and outputs a variable number of arguments

// to a character string using the vsnprintf() function

int sp(char * s, size_t n, char *format,...)

{

va_list args;

int retval;

va_start(args, format); // prepare the arguments

retval = vsnprintf(s, n, format, args);

va_end(args); // clean the stack

return retval;

}

Output:

n too small, dest = |Isab|, retval = 21

n right size, dest = |Isabelle is number 1|, retval = 21