C mbtowc() function

C mbtowc() function - Convert a character to a wide-character code

Syntax mbtowc() function

int mbtowc(whcar_t *pwc, const char *str, size_t n)

The mbtowc() function is used to first determine the length of the multibyte character pointed to by string. As described in mbstowcs, the multibyte character is then converted into a wide character. A maximum of n bytes are examined.

Parameters mbtowc() function

Name Description Required /Optional
pwc Address of a wide character (type wchar_t). Required
str Address of a sequence of bytes (a multibyte character). Required
n Number of bytes to check. Required

Return value from mbtowc()

If string is NULL:

  • Nonzero when the active locale is mixed byte.
  • 0 otherwise.

If string is not NULL:

  • The number of bytes that make up the converted multibyte character.
  • 0 if string points to the null character.
  • -1 if string does not point to a valid multibyte character.

Example: mbtowc() function

The following example shows the usage of mbtowc() function.

#include <stdio.h>
#include <stdlib.h>
#include <locale.h> 
#define LOCNAME "qsys.lib/mylib.lib/ja_jp959.locale"
/*Locale created from source JA_JP and CCSID 939 */
int length, temp;
char string [] = "\x0e\x41\x71\x0f\x41";
wchar_t text[6];
int main(void)
   /* initialize internal state variable */
   temp = mbtowc(text, NULL, 0);            
   setlocale(LC_ALL, LOCNAME);
   /* Set string to point to a multibyte character. */
   length = mblen(string, MB_CUR_MAX);
   temp = mbtowc(text,string,length);
   text[1] = L'\0';
   printf("Wide character string: %ls",text);


Wide character string: ♫

C Programming Code Editor:

Previous C Programming: C mbstowcs()
Next C Programming: C wcstombs()

Follow us on Facebook and Twitter for latest update.