wcrtomb() — Convert a wide character to a multibyte character

Standards

Standards / Extensions C or C++ Dependencies

ISO C Amendment
C99
Single UNIX Specification, Version 3

both  

Format

Non-XPG4:
#include <wchar.h>

size_t wcrtomb(char * __restrict__s, wchar_t wchar, mbstate_t * __restrict__pss);
XPG4:
#define _XOPEN_SOURCE
#define _MSE_PROTOS
#include <wchar.h>

size_t wcrtomb(char *s, wchar_t wchar, mbstate_t *pss);

General description

If s is a NULL pointer, the wcrtomb() function determines the number of bytes necessary to enter the initial shift state (zero if encodings are not state-dependent or if the initial conversion state is described). The resulting state described is the initial conversion state.

If s is not a NULL pointer, the wcrtomb() function determines the number of bytes needed to represent the multibyte character that corresponds to the wide character given by wchar (including any shift sequences), and stores the resulting bytes in the array whose first element is pointed to by s. At most, MB_CUR_MAX bytes are stored. If wchar is a NULL wide character, the resulting state described is the initial conversion state.

wcrtomb() is a “restartable” version of wctomb(). That is, shift state information is passed as one of the arguments and is updated on return. With wcrtomb(), you can switch from one multibyte string to another, provided that you have kept the shift-state information for each multibyte string.

The behavior of this wide-character function is affected by the LC_CTYPE category of the current locale. If you change the category, undefined results can occur.

Special behavior for XPG4: If you define any feature test macro specifying XPG4 behavior before the statement in your program source file to include the wchar header, then you must also define the _MSE_PROTOS feature test macro to make the declaration of the wcrtomb() function in the wchar header available when you compile your program. Please see Table 1 for a list of XPG4 and other feature test macros.

Returned value

If s is a NULL pointer, wcrtomb() returns the number of bytes needed to enter the initial shift state. The value returned will not be greater than that of MB_CUR_MAX.

If s is not a NULL pointer, wcrtomb() returns the number of bytes stored in the array object (including any shift sequences) when wchar is a valid wide character. Otherwise, when wchar is not a valid wide character, an encoding error occurs, the value of the macro EILSEQ is stored in errno and -1 is returned, but the conversion state remains unchanged.

Example

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

int main(void)
{
   char    *string;
   wchar_t wc;
   size_t  length;
   length = wcrtomb(string, wc, NULL);
}

Related information