6.23.31 wcrtomb Function

Convert a wide character to a multibyte character sequence.

Attention: This function is implemented only by MPLAB XC32 C compilers.

Include

<wchar.h>

Prototype

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

Arguments

s
the mulitbyte character sequence to convert
wc
a pointer to the array to hold the wide character
ps
a pointer to a mbstate_t object that holds the current conversion state

Return Value

The function returns the number of bytes stored in the array object s (including any shift sequences). If wc is not a valid wide character, (size_t)(-1) is returned.

Remarks

If s is a null pointer, the function is equivalent to the call wcrtomb(buf, L'\0', ps), where buf represents an internal buffer

If s is not a null pointer, the function determines the number of bytes needed to represent the multibyte character sequence that corresponds to the wide character given by wc (including any shift sequences), and stores at most MB_CUR_MAX bytes of that multibyte character representation in the array whose first element is pointed to by s. If wc is a null wide character, a null byte is stored, preceded by any shift sequence needed to restore the initial shift state; the resulting state described is the initial conversion state.

An encoding error occurs if wc is not a valid wide character, and the function will store the value of the macro EILSEQ in errno and the conversion state is unspecified.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

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

int main(void) {
  const wchar_t * pt = L"The wide ocean";
  char buffer [MB_CUR_MAX];
  size_t length, i;
  mbstate_t mbs;
  char needNL = 0;

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

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

Example Output

[T][h][e][ ][w][i][d][e][ ][o][c][e][a][n]