_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);
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
Upon success: Number of wide characters written
Upon failure: -1
dest
or format
is NULL
, then -1
is returned and errno
is set to EINVAL
count
is less than zero, then -1
returned and errno
is set to EINVAL
destsz
is smaller than the characters to be written, then 1
returned and errno
is set to ERANGE
count
is not equal to _TRUNCATE
, then 1
returned and errno
is set to ERANGE
NOTE: When
count
is equal to_TRUNCATE
,_vsnwprintf
writes as much of the wide string that fits in the destination buffer, leaving room for theNULL
terminating wide character.
#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;}
Number of wide characters written: 19, Destination buffer: Writing wide string
Number of wide characters written: 29, Destination buffer: Writing formatted wide string
_vsnwprintf_s
is 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
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