What is wcstombs_s in C?
The wcstombs_s() function converts a wide character data type to a multibyte character. wcstombs_s() is defined in the <stdlib.h> header file, so it is important that you include this library at the beginning of your code as shown below:
#include<stdlib.h>
The <stdlib.h> library defines the wcstombs_s() function as the following:
errno_t wcstombs_s(
size_t *pReturnValue,
char *mbstr,
size_t sizeInBytes,
const wchar_t *wcstr,
size_t count
);
Parameter
The wcstombs_s() function has four mandatory parameters:
pReturnValue: the size of the converted string in bytesmbstr: a pointer to the character array where the resultant string is storedsizeInBytes: size of thembstrarray in byteswcstr: pointer to the string that needs to be convertedcount: maximum number of bytes that one can store inmbstr.
Note:
wcstombs_s()can usually keep converting the wide character string until it terminates or the size ofmbstris equal tocount, but ifcountis set toTRUNCATE,wcstombs_s()can keep converting until the whole wide character string is converted.
Return value
The return value for wcstombs_s() is errno_t, which indicates whether the program was executed successfully or if an error occurred. If the return value is , the program was executed successfully. On the other hand, a non-zero return value indicates that an error occurred.
An error could occur in the following scenarios:
- If
mbstrisNULLandsizeInBytesis greater than zero. - If
wcstrisNULL. - If the
countvalue is too small to store the converted string.
Example
Following is an example of how you can use the wcstombs_s() function:
#include<stdio.h>#include<stdlib.h>#define SIZE 100int main() {size_t output_size;char* output = (char *)malloc( SIZE );wchar_t * str_to_convert = L"Educative is Great";wcstombs_s(&output_size, output, (size_t)SIZE,str_to_convert, (size_t)SIZE );//printing the outputsprintf("Number of characters convertes: %u\n", output_size);printf("Multibyte character: %s\n\n",output );return 0;}
Explanation
We define a size of 100 beforehand for the sizeInBytes and count variables. After defining the character pointer that will store the output string and the wide character pointer that stores the string to be converted, we use the wcstombs_s() function to convert to a multibyte character.
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 wcstombs (char* dest, const wchar_t* src, size_t max);
Free Resources