Open In App

mbtowc function in C

Last Updated : 29 Nov, 2017
Improve
Improve
Like Article
Like
Save
Share
Report

Convert multibyte sequence to wide character. The multibyte character pointed by pmb is converted to a value of type wchar_t and stored at the location pointed by pwc. The function returns the length in bytes of the multibyte character.
mbtowc has its own internal shift state, which is altered as necessary only by calls to this function. A call to the function with a null pointer as pmb resets the state (and returns whether multibyte characters are state-dependent).
The behavior of this function depends on the LC_CTYPE category of the selected C locale(C localization library).

Syntax:

pwc: Pointer to an object of type wchar_t.
Alternatively, this argument can be a null pointer, 
in which case the function does not store the wchar_t translation, 
but still returns the length in bytes of the multibyte character.

pmb: Pointer to the first byte of a multibyte character.
Alternatively, this argument can be a null pointer, 
in which case the function resets its internal shift 
state to the initial value and returns whether 
multibyte characters have a state-dependent encoding.

max: Maximum number of bytes of pmb 
to consider for the multibyte character.

Return Value: If the argument passed as pmb is not a null pointer, 
the size in bytes of the multibyte character pointed by pmb is returned 
when it forms a valid multibyte character and is not the terminating 
null character. If it is the terminating null character, the function 
returns zero, and in the case they do not form a valid multibyte character, -1 is returned.
If the argument passed as pmb is a null pointer, 
the function returns a nonzero value if multibyte character 
encodings are state-dependent, and zero otherwise.




// C program to illustrate mbtowc
// function
#include <stdio.h>
#include <stdlib.h> // function containing mbtowc & wchar_t(C) function
  
void mbtowc_func(const char* pt, size_t max)
{
    int length;
  
    // this is a typedef of an integral type
    wchar_t dest;
  
    // reset mbtowc
    mbtowc(NULL, NULL, 0);
  
    while (max > 0) {
        length = mbtowc(&dest, pt, max);
        if (length < 1) {
            break;
        }
  
        // printing each character in square braces
        printf("[%lc]", dest);
        pt += length;
        max -= length;
    }
}
  
int main()
{
    const char str[] = "geeks portal";
  
    mbtowc_func(str, sizeof(str));
  
    return 0;
}


Output:

[g][e][e][k][s][ ][p][o][r][t][a][l]

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads