Name

mbsrtowcs

Synopsis

Converts a multibyte string to a wide-character string

#include <stdlib.h>
size_tmbsrtowcs( wchar_t * restrict dest, const char * restrict src,
                  size_t n, mbstate_t * restrict state );

The mbsrtowcs() function, like mbstowcs(), converts a multibyte string to a wide character string, and returns the number of wide characters in the result, not counting the terminating null wide character. However, mbsrtowcs() also stores the resulting parse state of the multibyte string in the mbstate_t object addressed by the state argument. If mbsrtowcs() encounters an invalid multibyte character, it returns -1 and sets the errno variable to EILSEQ (“illegal sequence”).

The conversion performed is equivalent to calling mbrtowc() for each multibyte character in the original string, beginning in the shift state represented by the mbstate_t object addressed by the state argument.

Example

size_t result;

char mbstring[ ] = "This is originally a multibyte string.\n";
const char *mbsptr = mbstring;

wchar_t widestring[256] = { L'\0' };

mbstate_t state;
memset( &state, '\0', sizeof state );

printf( "The current locale is %s.\n", setlocale( LC_CTYPE, "" ));

result =mbsrtowcs( widestring, &mbsptr, 256, &state );
if ( result == (size_t)-1 )
{
  fputs( "Encoding error in multibyte string", stderr );
  return -1;
}
else
{
  printf( "Converted %u multibyte characters. The result:\n", result );
  printf( "%ls", widestring );
}

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.