What is vswprintf_s() in C?
vswprintf_s() prints a formatted list of arguments to a sized buffer; vswprint_s() validates the arguments at runtime before printing them. The declaration for vswprintf_s() is shown below:
int vswprintf_s( wchar_t *buffer, size_t size, const wchar_t *format, va_list args);
Note: The
vswprintf_sfunction is not supported by some compilers. If a compiler supportsvswprintf_s, the value ofSTDC_WANT_LIB_EXT1is set to 1.
Parameters
buffer: Pointer to the output string where output is to be printed.size: Maximum characters that can be written tobuffer.format: Format in which the output will be printed.args: Pointer to the list of arguments to be printed.
Return value
The vswprintf_s() function returns the number of characters written to buffer if the data is written successfully. A negative value is returned if there is an error when writing.
Note: The return value of
vswprintf_s()does not count terminating null characters.
Example
Consider the code snippet below, which demonstrates the use of vswprintf_s():
#include <stdio.h>#include <wchar.h>#include <stdarg.h>int writeformatted (wchar_t buffer[], const wchar_t * format, ...){int len = 0;va_list arg;va_start (arg, format);len = vswprintf_s (buffer, 80, format, arg);va_end (arg);return len;}int main (){wchar_t buffer[80];int len = writeformatted(buffer, L"vswprintfExample: %s\n", "writing to buffer");printf("%S\n",buffer);printf("Number of character written to buffer: %d",len);return 0;}
Output
vswprintfExample: writing to buffer
Number of character written to buffer: 36
Explanation
The writeformatted() function is used in line 19, which uses vswprintf_s() in line 10 to write to the buffer.
Note: The function above is not supported by the GCC compiler, hence you will get an implicit declaration of function
vswprintf_serror. Use the following variant to get the job done:int vswprintf( wchar_t *buffer, size_t size, const wchar_t *format, va_list args);.
Free Resources