C programming stdlib.h function - int wctomb(char *str, wchar_t wchar)

www.igift‮.aedi‬com

The wctomb function from stdlib.h header file in C programming language is used to convert a wide character to its corresponding multibyte representation.

The syntax of the function is:

int wctomb(char *str, wchar_t wchar);

Here,

  • str: A pointer to the multibyte string where the corresponding multibyte character will be stored.
  • wchar: A wide character to be converted to its corresponding multibyte representation.

The function returns the number of bytes written to the multibyte string str, except for the null terminating byte.

If the value of the wchar parameter is not a valid wide character, the function returns -1. If the str parameter is NULL, the function just determines the number of bytes required to represent the character and returns that value.

Example usage:

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

int main() {
    wchar_t wc = L'€';  // A euro symbol
    char mb[MB_CUR_MAX];
    int num_bytes = wctomb(mb, wc);
    if (num_bytes == -1) {
        printf("Invalid wide character.\n");
        return 1;
    }
    printf("Multibyte representation: ");
    for (int i = 0; i < num_bytes; i++) {
        printf("%02x ", (unsigned char) mb[i]);
    }
    printf("\n");
    return 0;
}

Output:

Multibyte representation: e2 82 ac