mbtowc() — Convert multibyte character to wide character

Standards

Standards / Extensions C or C++ Dependencies

ISO C
XPG4
XPG4.2
C99
Single UNIX Specification, Version 3

both  

Format

#include <stdlib.h>

int mbtowc(wchar_t * __restrict__pwc, const char* __restrict__string, size_t n);

General description

Converts a multibyte character to a wide character and returns the number of bytes of the multibyte character. It first determines the length of the multibyte character pointed to by string. It then converts the multibyte character to the corresponding wide character and places the wide character in the location pointed to by pwc, if pwc is not a NULL pointer. A maximum of n bytes is examined.

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.

Returned value

If string is NULL, mbtowc() returns:
  • Nonzero if the multibyte encoding in the current locale (LC_CTYPE) is shift-dependent.
  • 0 otherwise.
  • The current shift state is set to the initial state.
Otherwise if string is not NULL, mbtowc() returns:
  • The number of bytes comprising the converted multibyte character, if n or fewer bytes form a valid multibyte character.
  • 0 if string points to the NULL character.
  • -1 if string does not point to a valid multibyte character, and the next n bytes do not form a valid multibyte character.

If the current locale supports EBCDIC DBCS characters, the shift state is updated where applicable. The length returned may be up to 4 characters long (for the shift-out character, 2-byte code, and the shift-in character).

After the function is placed into its initial state, it interprets multibyte characters—pointed to by string—accordingly. During the processing of shift-dependent encoded characters, you cannot stop processing one string, then move temporarily to processing another string, and return to the first, because the state would be valid for the second string, not the place where you stopped in the first string.

Example

/* This example uses mbtowc() to convert a multibyte character into a wide
   character.
 */
#include <stdio.h>
#include <stdlib.h>

int temp;
char string [6];
wchar_t arr[6];

int main(void)
{ /* Set string to point to a multibyte character. */
⋮
   temp = mbtowc(arr, string, MB_CUR_MAX);
   printf("wide-character string: %ls",arr);
}

Related information