What is wcsrtombs_s in C?
The wcsrtombs_s() function converts the wide-character null-terminated string to multibyte characters. wcsrtombs_s() is defined in the <wchar.h> header files, so it is important to include this library at the beginning of your code as shown below:
#include<wchar.h>
The <wchar.h> header file defines wcsrtombs_s() as shown below:
errno_t wcsrtombs_s(
size_t *pReturnValue,
char *mbstr,
size_t sizeInBytes,
const wchar_t **wcstr,
sizeof count,
mbstate_t *mbstate
);
Parameters
The wcsrtombs_s() function requires 6 parameters in total:
pReturnValue: the size of the converted string in bytesmbstr: the pointer to a character array, which stores the resultant multibyte character- 'sizeInBytes
: the size of thembstr` character array wcstr: pointer to the wide character that shall be converted to multibyte charactercount: this is the maximum number of bytes that should be stored in thembstrarraymbstate: a pointer of typembstate_t(mbstate_tstores the state of a conversion in multibyte encoding)
Return value
The return value for wcsrtombs_s() is of type errno_t. If wcsrtombs_s()is executed successfully, it returns a 0 and modifies pReturnValuesuccessfully. On the other hand, if an error occurs during execution, the wcsrtombs_s() function returns a non-zero error. Below are some reasons why an error could occur:
countis too small to store the converted multibyte character stringmbstrisNULLbutsizeInBytesis greater than 0wcstrisNULL
Moreover, if a wide character that cannot be converted is found during conversaion, the wcsrtombs_s() function returns EILSEQ error, and sets mbstr as NULL and pReturnValue as -1.
Example
Below is an example of how you can use the wcsrtombs_s() function:
#include <stdio.h>#include <errno.h>#include <wchar.h>#define SIZE 100int main(){//define the variables firstconst wchar_t stringToConvert[] = L"Educative is great.";const wchar_t *store = stringToConvert;char outputString[SIZE];size_t countSize;errno_t error;mbstate_t state;// Reset the mbstate to initial shift state::memset((void*)&state, 0, sizeof(state));error = wcsrtombs_s(&countSize, outputString, SIZE,&store, SIZE, &state);if (error == EILSEQ){printf( "Error econding.\n" );}else{printf( "Successful conversion of string.\n" );}}
Explanation
First, we include all the necessary libraries, such as <wchar.h>. Then, we add <errno.h> to store the errors in errno_t type variable. After defining all the necessary variables, we execute wcsrtombs_s() and store the error returned in a variable of type errno_t. This helps us determine whether the string was successfully converted or if an error occurred.
The function above is not supported by the GCC compiler, so you will get an implicit declaration of function… error. Use the following variant to get the job done:
size_t wcsrtombs(
char *mbstr,
const wchar_t **wcstr,
sizeof count,
mbstate_t *mbstate
);
Free Resources