function
<cwchar>

wcrtomb

size_t wcrtomb (char* pmb, wchar_t wc, mbstate_t* ps);
Convert wide character to multibyte sequence
The wide character wc is translated to its multibyte equivalent and stored in the array pointed by pmb. The function returns the length in bytes of the equivalent multibyte sequence pointed by pmb.

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.

A call to the function with a null pointer as pmb also resets the shift state (and ignores parameter wc).

The behavior of this function depends on the LC_CTYPE category of the selected C locale.

This is the restartable version of wctomb (<cstdlib>).

Parameters

pmb
Pointer to an array large enough to hold a multibyte sequence.
The maximum length of a multibyte sequence for a character in the current locale is MB_CUR_MAX bytes.

Alternativelly, the function may be called with a null pointer, in which case the function always resets the shift state to the initial state, as if wc was L'\0' (ignoring the actual value passed as wc).
wc
Wide character of type wchar_t.
ps
Pointer to a mbstate_t object that defines a conversion state.

If this is a null pointer, the function uses its own internal shift state, which is initialized on program startup and is only altered by calls to this function.

Return Value

The size of the multibyte sequence written at pmb (in bytes), including any shift characters.

If there is no character correspondence, the function returns (size_t)-1 and sets errno to EILSEQ.

If pmb is a null pointer, the function returns one plus the number of bytes needed to restore the initial shift state (as if the function operated on an internal buffer and wc was L'\0').

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* wcrtomb example */
#include <wchar.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
  const wchar_t* pt = L"wcrtomb example";
  char buffer [MB_CUR_MAX];
  size_t length, i;
  mbstate_t mbs;

  mbrlen (NULL,0,&mbs);   /* initialize mbs */

  while (*pt) {
    length = wcrtomb(buffer,*pt,&mbs);
    if ((length==0)||(length>MB_CUR_MAX)) break;
    putchar ('[');
    for (i=0;i<length;++i) putchar (buffer[i]);
    putchar (']');
    ++pt;
  }

  return 0;
}

The example prints the multibyte characters that a wide character string translates to using the selected locale (in this case, the "C" locale).

Output:

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


See also