The swprintf_s
is defined in the wchar.h
header file and is the security-enhanced alternate of the swprintf
function. It uses a wide format string and its corresponding arguments to generate a wide string that stores in the provided wide string. What makes swprintf_s
different from the normal swprintf
is that it performs extra run-time checks on the arguments before they are executed.
Following is the syntax for the swprintf_s
function:
The swprintf_s
function takes in 4 arguments:
ws
: The pointer to the destination wide string where the formatted wide string will be stored.
len
: The maximum length of the string that will be stored. Any characters appearing after this length in the formatted wide string will be discarded.
format
: The pointer to the format string which may include format specifiers like %ls
.
...
: The list of arguments corresponding to the specifiers used (if any) in the format string. This can have from zero to as many arguments as the number of specifiers used in the format
wide string.
swprintf_s
can have two potential returns values:
A negative number if there is any error in execution or the length of the formatted string is greater than the given length.
The number of characters in the formatted string in case of successful execution of the function.
Following is an example of how we can use the swprintf_s
function to generate and copy a formatted wide string to a pointed wide string:
All bounds-checked functions (with “_s” suffix in their names) including the
swprintf_s
function are only guaranteed to work if__STDC_LIB_EXT1__
is pre-defined by the implementation and if the user defines__STDC_WANT_LIB_EXT1__
toint
1 before includingstdio.h
header file.
//__STDC_WANT_LIB_EXT1__ has to be defined to int 1 for swprintfs to work#define __STDC_WANT_LIB_EXT1__ 1;#include <stdio.h>#include <wchar.h>int main (){// destination wide string arraywchar_t dest_str [50];// wide string array to use as argumentwchar_t var [10] = L"a ton";// int variable to store the return value of swprintf_sint ch_count;// only use swprintf_s if __STDC_LIB_EXT1__ is already defined#ifdef __STDC_LIB_EXT1__ch_count = swprintf_s ( dest_str, 50, L"Educative has %ls courses", var );#endif// use swprintf functionch_count = swprintf ( dest_str, 50, L"Educative has %ls courses", var );// printing out the destination wide stringwprintf(dest_str);return 0;}
In this example, we declare two wide strings and initialized the one we intend to use as the argument corresponding to the specifier used in the format string. We now check if __STDC_LIB_EXT1__
is defined and then use the swprintf_s
function. We pass the function a format string, and the argument we create.swprint_s
then generates the formatted output and stored it in the destination wide string. Finally, we print out the complete wide string using the wprintf
.
Free Resources