To understand the wctomb_s()
function, you first need to understand the following terms:
wide character
: A data type similar to the char
data type in C. While char
takes up 1-byte memory and represents only values, the wide character can take up to (2 bytes) corresponding to UNICODE values.
multibyte encoding: As there is a need to ensure that more characters can be encoded, we use varying number of bytes to encode a character. While the first byte ensures backward compatability, the rest can be used for representation beyond characters.
The wctomb_s()
function, similar to the wctomb()
function, converts the wide character
variable wc
to multibyte encoding. It is stored in the array pointed to by the variable s
. wctomb_s()
is defined in the <stdlib.h>
header file, so it is important to include the library at the beginning of your code as shown below:
#include<stdlib.h>
The wctomb_s()
function is defined as the following in the <stdlib.h>
library:
errno_t wctomb_s(
int *pRetValue,
char *mbchar,
size_t sizeInBytes,
wchar_t wchar
);
The wctomb_s()
function requires 4 parameters:
pRetValue
: a pointer to where the output will be stored.mbchar
: a character array that points to the output of the multibyte encoding.sizeInBytes
: the size of the array mbchar
, meaning the maximum bytes to be written to mbchar
. sizeInBytes
can never be greater than MB_CUR_MAX
, which is the maximum number of bytes needed to represent a multibyte character for your machine.wchar
: the wide character you need to convert to multibyte encoding.The return data type for the wctomb_s()
function is errno_t
. errno_t
detects whether the function returns any errors. The following table represents each of the values that can be returned and what they mean:
Value | Meaning |
0 | Successful execution |
Non-zero | Encoding error or runtime constraint violation |
If the wctomb_s()
function is executed successfully, then the multibyte encoding will be stored in s
, and status
will store the length of the multibyte encoding. On the other hand, an error could also occur for the following reasons:
mbchar
is NULL but sizeInBytes
is greater than zero.sizeInBytes
is either too big or too small.The example below shows how you can use the wctomb_s()
function:
#include <stdio.h>#include <stdlib.h>int main(){int i;wchar_t wide_char = L'C';char *output = (char *)malloc( MB_CUR_MAX );printf( "Converting a wide character to multibyte encoidng:\n" );wctomb_s( &i, output, MB_CUR_MAX, wide_char );printf( "Multibyte character output: %.1s\n", output );return 0;}
Note:
L
is a prefix for wide character data type.
The wctomb_s()
function converts the character ‘C’ to its multibyte encoding and prints it.
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:
int wctomb (char* pmb, wchar_t wc);
Free Resources