C Reference function mbtowc()

The function mbtowc(), that is part of the stdlib.h library, is used to convert a multi-byte character to wide character.

Usage of mbtowc():

int mbtowc ( wchar_t * pwc, const char * pmb, size_t max );

The multibyte character pointed by pmb (pointer multibyte character) is converted to a wide character which is stored at the location that is pointed by pwc (pointer wide character). The length in bytes of the multiby character is returned.

The mbtowc function has its own internal shift state, which can only be altered by this function.

Parameters:

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

pmb is a pointer to the first byte of a multi-byte character. If it is a null pointer then the function resets its internal shift state to the initial value and returns whether multi-byte characters have state-dependent encodings or not.

max is the maximum number of bytes to be checked for character length.
No more than MB_CUR_MAX characters are examined in any case.

Return value:

If pmb is NULL then the mbtowc() function returns a nonzero when the active locale is mixed byte the function initializes the state variable, otherwise 0 is returned.

If pmb is not NULL then the mbtowc() function returns a 0 if string points to the null character, the number of bytes comprising the converted multibyte character or -1 if pmb does not point to a valid multi-byte character.

If a conversion error occurs, errno may be set to ECONVERT.

Source code example of mbtowc():


	#include<stdio.h>
	#include<stdlib.h>

	int length, temp;
	char strdata [6] = "m";
	wchar_t my_array[6];

	int main(void)
	{
		/* initialize internal state variable */
		length = mblen(NULL, MB_CUR_MAX); 

		/* set strdata to point to a multibyte character  */
		length = mblen(strdata, MB_CUR_MAX);

		temp = mbtowc(arr,strdata,length);

		my_array[1] = L'\0';
		printf("wide character strdata: %ls\n", my_array);
	}

This entry was posted in C Reference stdlib.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

Comments are closed.