Previous Page
Next Page

mbtowc

Converts a multibyte character to a wide character

#include <stdlib.h>
int mbtowc ( wchar_t * restrict wc , const char * restrict s ,
            size_t maxsize  );

The mbtowc( ) function determines the wide character corresponding to the multibyte character referenced by the second pointer argument, and stores the result in the location referenced by the first pointer argument. The third argument is the maximum number of bytes to read for the multibyte character, and the return value is the number of bytes that the function actually read to obtain a valid multibyte character. If the second argument points to a null character, mbtowc( ) returns 0. If it does not point to a valid multibyte character, mbtowc( ) returns -1.

If you pass mbtowc( ) a null pointer as the second argument, s, then the return value indicates whether the current multibyte encoding is stateful. This behavior is the same as that of mblen( ). If mbtowc( ) returns 0, then the encoding is stateless. If it returns any other value, the encoding is stateful; that is, the interpretation of a given byte sequence may depend on the shift state.

Example

The following example converts an array of multibyte characters into wide characters one at a time, and prints each one:

int i = 0, n = 0;
wchar_t wc;
char mbstring[256] = "This is originally a multibyte string.\n";

printf( "The current locale is %s.\n", setlocale(LC_CTYPE, "" ));

while ( (n = mbtowc( &wc, &mbstring[i], MB_CUR_MAX )) != 0 )
{
  if ( n == -1 )
  {
    fputs( "Encoding error in multibyte string", stderr );
    break;
  }
  printf( "%lc", (wint_t)wc );
  i += n;
};

See Also

mbrtowc( ), mblen( ), mbsinit( )


Previous Page
Next Page