C Library Function - wctomb()
C Standard Library - <stdlib.h>
Description
The C library function int wctomb(char *str, wchar_t wchar) converts the wide character wchar into its multibyte representation and stores it at the beginning of the character array pointed to by str.
Declaration
Here is the declaration for the wctomb() function.
int wctomb(char *str, wchar_t wchar)
Parameters
str -- A pointer to an array large enough to store a multibyte character.
wchar -- A wide character of type wchar_t.
Return Value
If str is not NULL, the wctomb() function returns the number of bytes written to the byte array. If wchar cannot be represented as a multibyte sequence, it returns -1.
If str is NULL, the wctomb() function returns non-zero if the encoding has a shift state, and zero if the encoding is stateless.
Example
The following example demonstrates the use of the wctomb() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
wchar_t wc = L'a';
char *pmbnull = NULL;
char *pmb = (char *)malloc(sizeof( char ));
printf("Wide character to be converted:\n");
i = wctomb( pmb, wc );
printf("Converted characters: %u\n", i);
printf("Multibyte character: %.1s\n", pmb);
printf("Attempting conversion when the character to be converted is NULL:\n");
i = wctomb( pmbnull, wc );
printf("Converted characters: %u\n", i);
/* No value will be printed */
printf("Multibyte character: %.1s\n", pmbnull);
return(0);
}
Let's compile and run the above program, which will produce the following result:
Wide character to be converted:
Converted characters: 1
Multibyte character: a
Attempting conversion when the character to be converted is NULL:
Converted characters: 0
Multibyte character: