int vsnprintf (char * s, size_t n, const char * format, va_list arg );
Write formatted data from variable argument list to sized buffer
Composes a string with the same text that would be printed if format was used on printf, but using the elements in the variable argument list identified by arg instead of additional function arguments and storing the resulting content as a C string in the buffer pointed by s (taking n as the maximum buffer capacity to fill).
If the resulting string would be longer than n-1 characters, the remaining characters are discarded and not stored, but counted for the value returned by the function.
Internally, the function retrieves arguments from the list identified by arg as if va_arg was used on it, and thus the state of arg is likely to be altered by the call.
In any case, arg should have been initialized by va_start at some point before the call, and it is expected to be released by va_end at some point after the call.
- Pointer to a buffer where the resulting C-string is stored.
The buffer should have a size of at least n characters.
- Maximum number of bytes to be used in the buffer.
The generated string has a length of at most n-1, leaving space for the additional terminating null character.
size_t is an unsigned integral type.
- C string that contains a format string that follows the same specifications as format in printf (see printf for details).
- A value identifying a variable arguments list initialized with va_start.
va_list is a special type defined in <cstdarg>.
The number of characters that would have been written if n had been sufficiently large, not counting the terminating null character.
If an encoding error occurs, a negative number is returned.
Notice that only when this returned value is non-negative and less than n, the string has been completely written.
/* vsnprintf example */
void PrintFError ( const char * format, ... )
va_start (args, format);
vsnprintf (buffer,256,format, args);
int main ()
FILE * pFile;
pFile = fopen (szFileName,"r");
if (pFile == NULL)
PrintFError ("Error opening '%s'",szFileName);
// file successfully open
In this example, if the file myfile.txt does not exist, perror is called to show an error message similar to:
Error opening file 'myfile.txt': No such file or directory
- Write formatted data from variable argument list to stream (function)
- Print formatted data from variable argument list to stdout (function)
- Write formatted data to string (function)
- Print formatted data to stdout (function)