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 resets the shift state (either ps or its own internal state) to the initial state and returns zero.
wc
Wide character of type wchar_t.
ps
Pointer to a mbstate_t object that defines a conversion state.

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 stores no bytes at pmb, and thus returns zero.

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
25
/* 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];
  int i;
  size_t length;
  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