C Library Function - mblen()
C Standard Library - <stdlib.h>
Description
The C library function int mblen(const char *str, size_t n) returns the length of the multibyte character pointed to by str.
Declaration
Here is the declaration for the mblen() function.
int mblen(const char *str, size_t n)
Parameters
str -- Pointer to the first byte of a multibyte character.
n -- Maximum number of bytes to be checked for character length.
Return Value
If a non-null wide character is identified, the mblen() function returns the number of bytes parsed in the multibyte sequence starting from str. If a null wide character is identified, it returns 0. If an invalid multibyte sequence is identified, or a complete multibyte character cannot be parsed, it returns -1.
Example
The following example demonstrates the use of the mblen() function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int len;
char *pmbnull = NULL;
char *pmb = (char *)malloc( MB_CUR_MAX );
wchar_t *pwc = L"Hi";
wchar_t *pwcs = (wchar_t *)malloc( sizeof( wchar_t ));
printf("Converting to multibyte string\n");
len = wcstombs( pmb, pwc, MB_CUR_MAX);
printf("Characters converted %d\n", len);
printf("Hexadecimal value of the first multibyte character: %#.4x\n", pmb);
len = mblen( pmb, MB_CUR_MAX );
printf( "Length in bytes of multibyte character %x: %u\n", pmb, len );
pmb = NULL;
len = mblen( pmb, MB_CUR_MAX );
printf( "Length in bytes of multibyte character %x: %u\n", pmb, len );
return(0);
}
Let's compile and run the above program, which will produce the following result:
Converting to multibyte string
Characters converted 1
Hexadecimal value of the first multibyte character: 0x168c6010
Length in bytes of multibyte character 168c6010: 1
Length in bytes of multibyte character 0: 0