What is _vsnwprintf_s in C?
_vsnwprintf_s in C writes formatted wide strings to a destination buffer and returns the number of wide characters written. _vsnwprintf_s is defined in the wchar.h header file and the function prototype is as follows:
int _vsnwprintf_s(wchar_t *dest, size_t destsz, size_t count, const wchar_t *format, va_list argptr);
Parameters
dest: Destination buffer of formatted wide string
destsz: Maximum size of destination buffer in bytes
count: Number of wide characters to write; does not include terminating NULL character
format: Format specification
argptr: Pointer to list of arguments
Return value
Upon success: Number of wide characters written
Upon failure: -1
Error handling
- If
destorformatisNULL, then-1is returned anderrnois set toEINVAL - If
countis less than zero, then-1returned anderrnois set toEINVAL - If
destszis smaller than the characters to be written, then1returned anderrnois set toERANGE - If
countis not equal to_TRUNCATE, then1returned anderrnois set toERANGE
NOTE: When
countis equal to_TRUNCATE,_vsnwprintfwrites as much of the wide string that fits in the destination buffer, leaving room for theNULLterminating wide character.
Example
#include <stdio.h>#include <wchar.h>#include <wtypes.h>void formatted_widestring(wchar_t* format_widestring, ...){int chars_written = 0;wchar_t dest[30];va_list args;va_start(args, format_widestring);chars_written = _vsnwprintf_s(dest, sizeof(dest), _TRUNCATE, format_widestring, args);wprintf(L"Number of wide characters written: %d, Destination buffer: %ls\n", chars_written, dest);va_end(args);}int main(){formatted_widestring(L"%ls %ls %ls", L"Writing", L"wide", L"string");formatted_widestring(L"%ls %ls %ls %ls", L"Writing", L"formatted", L"wide", L"string");return 0;}
Output
Number of wide characters written: 19, Destination buffer: Writing wide string
Number of wide characters written: 29, Destination buffer: Writing formatted wide string
_vsnwprintf_sis not supported by the GCC compiler, so you will get animplicit declaration of function… error. Use the following variant to get the job done:_vsnwprintf
Explanation
First, we import the necessary header files such as wchar.h for wide strings, and wtypes.h for variable arguments. The function formatted_widestring takes in a variable number of wide string arguments and prints them in formatted form using _vsnwprintf_s.
In lines 9-11, we initialize our destination buffer, start a variable argument list, and pass them to _vsnwprintf_s, where count is set to _TRUNCATE. Finally, we print the number of wide characters written and the destination buffer.
In lines 11, 18, and 19, the L identifier before the string indicates that the characters to follow are from the Unicode character set.
Free Resources