vsnprintf()
prints a formatted list of arguments to a character array. The declaration for vsnprintf()
is shown below:
int vsnprintf(char *arr, size_t len, const wchar_t *format, va_list args);
arr
: Pointer to the character array where output is to be printedlen
: Maximum number of characters that can be written to the arrayformat
: Format in which the output will be printedargs
: Pointer to the list of arguments to be printedIf the write operation to the output stream is successful, vsnprintf()
returns the number of characters written. A negative value is returned if there is an error when writing to the output stream.
Note: The return value of
vsnprintf()
does not count terminating null characters.
Consider the code snippet below, which demonstrates the use of vsnprintf()
:
#include <stdio.h>#include <stdarg.h>int writeformatted(char* buffer, int bufferSize, const char *format, ...){int len = 0;va_list arguments;va_start(arguments, format);len = vsnprintf(buffer, bufferSize, format, arguments);va_end(arguments);return len;}int main (){char buf[50];char s1[50] = "vsnprintf() Example Code";int len = writeformatted(buf, 50, "%s ", s1);printf("Content of array: %s \n", buf);printf("No. of characters in array: %d \n", len);return 0;}
The writeformatted()
function is used in line 20, which uses vsnprintf()
in line 9 to print the arguments that are created in lines 16-18 in buf
.
Free Resources