C Standard Library

C <wchar.h> - wcrtomb() Function

The C <wchar.h> wcrtomb() function converts a wide character to multibyte sequence.

If s is not a null pointer, the wide character wc is converted to its multibyte equivalent and stored in the character array whose first element is pointed to by s. The function returns the length in bytes of the equivalent multibyte sequence pointed by s. At most MB_CUR_MAX bytes can be written by this function.

If s is a null pointer, the function always resets the shift state to the initial state, as if wc was L'\0' (ignoring the actual value passed as wc) and the call is equivalent to wcrtomb(buf, L'\0', ps) for some internal buffer buf.

The function uses and updates the shift state described by ps. If ps is a null pointer, the function uses its own internal shift state, which is altered as necessary only by calls to this function.

If wc is a null wide character, the function resets the shift state and stores a null byte, preceded by any shift sequence needed to restore the initial shift state.


size_t wcrtomb (char* s, wchar_t wc, mbstate_t* ps);


s Specify pointer to an character array where the multibyte character will be stored.
wc Specify the wide character to convert.
ps Specify pointer to a mbstate_t object that defines a conversion state.

Return Value

On success, returns the number of bytes (including any shift characters) written to the character array s. On failure (if wc is not a valid wide character), returns (size_t)-1 and sets errno to EILSEQ.


In the example below, this function is used to convert all wide characters of a wide string into multibyte sequence.

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
int main (){
  size_t length;
  mbstate_t mbs;
  wchar_t wstr[] = L"wcrtomb example";
  char buffer[100];

  for(int i=0; i < wcslen(wstr); i++) {
    length = wcrtomb(buffer, wstr[i], &mbs);
    putchar ('[');
    for (int j=0; j<length; ++j) 
    putchar (']');
  return 0;

The output of the above code will be:

[w][c][r][t][o][m][b][ ][e][x][a][m][p][l][e]

❮ C <wchar.h> Library