C library - wctomb() function



The C stdlib library wctomb() function is used to convert the wide-character wchar to its multi-byte sequence and stores it at the starting of the character array pointed to by 'str' and returns the length in bytes of the equivalent multi-byte sequence.

This function is commonly used for encoding, which is essential when dealing with various character encodings in applications that require support for multiple languages.

Syntax

Following is the C library syntax of the wctomb() function −

int wctomb(char *str, wchar_t wchar)

Parameters

This function accepts following parameters −

  • str − It represent a pointer to an array, which is large enough to hold a multi-byte sequence,

  • wchar − It represents a wide character of type wchar_t to be converted.

Return Value

Following is the return values −

  • If 'str' is not 'NULL' and conversion is successful, then its return number of bytes written to the buffer.

  • If 'str' is 'NULL' then its return 0.

  • If conversion fails, then its return -1.

Example 1

Let's create a basic c program to demonstrate the use of wctomb() function.

#include <stdio.h>
#include <stdlib.h>

int main () {
   int i;
   wchar_t wchar = L'X';
   char *nullstr = NULL;
   char *str = (char *)malloc(sizeof( char ));

   i = wctomb( str, wchar );
   printf("Characters converted: %u\n", i);
   printf("Multibyte character: %.1s\n", str);

   printf("Trying to convert when string is NULL:\n");
   i = wctomb( nullstr, wchar );
   printf("Characters converted: %u\n", i);
   /* this will not print any value */
   printf("Multibyte character: %.1s\n", nullstr);
   
   return(0);
}

Output

Following is the output −

Characters converted: 1
Multibyte character: X
Trying to convert when string is NULL:
Characters converted: 0
Multibyte character: 

Example 2

The following example convert a wide-character to a multi-byte character using wctomb() function.

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>

int main() {
   setlocale(LC_ALL, "");
   
   // Japanese wide character to be converted
   wchar_t wchar = L'あ';
   
   // Buffer to hold the multibyte character
   char mbstr[MB_CUR_MAX];
   
   // Convert wide character to multibyte character
   int ret_val = wctomb(mbstr, wchar);
   
   // Check the return value of wctomb
   if (ret_val == -1) {
      printf("Conversion failed.\n");
   } else {
      printf("Converted multibyte character: ");
      for (int i = 0; i < ret_val; ++i) {
         printf("%02X ", (unsigned char)mbstr[i]);
      }
      printf("\nNumber of bytes written: %d\n", ret_val);
   }
   return 0;
}

Output

Following is the output −

Conversion failed.
Advertisements