Export (0) Print
Expand All
Expand Minimize


Convert a wide character into its multibyte character representation. A version of wcrtomb with security enhancements as described in Security Enhancements in the CRT.

errno_t wcrtomb_s(
   size_t *pReturnValue,
   char *mbchar,
   size_t sizeOfmbchar,
   wchar_t *wchar,
   mbstate_t *mbstate
template <size_t size>
errno_t wcrtomb_s(
   size_t *pReturnValue,
   char (&mbchar)[size],
   wchar_t *wchar,
   mbstate_t *mbstate
); // C++ only

[out] pReturnValue

Returns the number of bytes written or -1 if an error occurred.

[out] mbchar

The resulting multibyte converted character.

[in] sizeOfmbchar

The size of the mbchar variable in bytes.

[in] wchar

A wide character to convert.

[in] mbstate

A pointer to an mbstate_t object.

Returns zero or an errno value if an error occurs.

The wcrtomb_s function converts a wide character, beginning in the specified conversion state contained in mbstate, from the value contained in wchar, into the address represented by mbchar. The pReturnValue value will be the number of bytes converted, but no more than MB_CUR_MAX bytes, or an -1 if an error occurred.

If mbstate is null, the internal mbstate_t conversion state is used. If the character contained in wchar does not have a corresponding multibyte character, the value of pReturnValue will be -1 and the function will return the errno value of EILSEQ.

The wcrtomb_s function differs from wctomb_s, _wctomb_s_l by its restartability. The conversion state is stored in mbstate for subsequent calls to the same or other restartable functions. Results are undefined when mixing the use of restartable and nonrestartable functions. For example, an application would use wcsrlen rather than wcslen, if a subsequent call to wcsrtombs_s were used instead of wcstombs_s.


The wcrtomb_s function is multithread safe as long as no function in the current thread calls setlocale while this function is executing and the mbstate is null.

// crt_wcrtomb_s.c
// This program converts a wide character
// to its corresponding multibyte character.

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

int main( void )
    errno_t     returnValue;
    size_t      pReturnValue;
    mbstate_t   mbstate;
    size_t      sizeOfmbStr = 1;
    char        mbchar = 0;
    wchar_t*    wchar = L"Q\0";

    // Reset to initial conversion state
    memset(&mbstate, 0, sizeof(mbstate));

    returnValue = wcrtomb_s(&pReturnValue, &mbchar, sizeof(char),
                            *wchar, &mbstate);
    if (returnValue == 0) {
        printf("The corresponding wide character \"");
        wprintf(L"%s\"", wchar);
        printf(" was converted to a the \"%c\" ", mbchar);
        printf("multibyte character.\n");
        printf("No corresponding multibyte character "
               "was found.\n");
The corresponding wide character "Q" was converted to a the "Q" multibyte character.



Required header



Community Additions

© 2014 Microsoft