C Standard Library

C <stdlib.h> - mbtowc() Function



The C <stdlib.h> mbtowc() function converts a multibyte character whose first byte is pointed to by str to a wide character and stored at the location pointed by pwc, if pwc is not null. The function returns the length in bytes of the multibyte character.

This function has its own internal shift state, which is altered as necessary only by calling it. If str is a null pointer, it resets its internal conversion state to represent the initial shift state and returns whether multibyte encoding is state-dependent.

Syntax

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

Parameters

pwc Specify pointer to the wide character for output.
str Specify pointer to the multibyte character.
n Specify maximum number of bytes in str that can be examined.
size_t is an unsigned integral type.

Return Value

When str is not a null pointer, it returns the number of bytes that are contained in the multibyte character or -1 if the first bytes pointed to by str do not form a valid multibyte character or 0 if str is pointing at the null charcter '\0'.

When str is a null pointer, it returns 0 if the current multibyte encoding is not state-dependent or a non-zero value if the current multibyte encoding is state-dependent.

Example:

In the example below, mblen() and mbtowc() functions are used in the user-defined function printbuffer(), which prints a multibyte string character by character.

#include <stdio.h>
#include <stdlib.h>
 
void printbuffer (char* str, size_t n){
  int length;
  wchar_t dest;

  mblen (NULL, 0);         //reset mblen
  mbtowc (NULL, NULL, 0);  //reset mbtowc

  while (n > 0) {
    length = mblen(str, n);
    if (length < 1) 
      break;
    mbtowc(&dest, str, length);
    printf("[%lc]", dest);
    str = str + length; 
    n = n - length;
  }
}

int main (){
  char str [] = "Hello World!";
  printbuffer (str, sizeof(str));
  return 0;
}

The output of the above code will be:

[H][e][l][l][o][ ][W][o][r][l][d][!]

❮ C <stdlib.h> Library

5