Go to the first, previous, next, last section, table of contents.


Conversion of Extended Strings

The mbstowcs function converts a string of multibyte characters to a wide character array. The wcstombs function does the reverse. These functions are declared in the header file `stdlib.h'.

In most programs, these functions are the only ones you need for conversion between wide strings and multibyte character strings. But they have limitations. If your data is not null-terminated or is not all in core at once, you probably need to use the low-level conversion functions to convert one character at a time. See section Conversion of Extended Characters One by One.

Function: size_t mbstowcs (wchar_t *wstring, const char *string, size_t size)
The mbstowcs ("multibyte string to wide character string") function converts the null-terminated string of multibyte characters string to an array of wide character codes, storing not more than size wide characters into the array beginning at wstring. The terminating null character counts towards the size, so if size is less than the actual number of wide characters resulting from string, no terminating null character is stored.

The conversion of characters from string begins in the initial shift state.

If an invalid multibyte character sequence is found, this function returns a value of -1. Otherwise, it returns the number of wide characters stored in the array wstring. This number does not include the terminating null character, which is present if the number is less than size.

Here is an example showing how to convert a string of multibyte characters, allocating enough space for the result.

wchar_t *
mbstowcs_alloc (const char *string)
{
  size_t size = strlen (string) + 1;
  wchar_t *buf = xmalloc (size * sizeof (wchar_t));

  size = mbstowcs (buf, string, size);
  if (size == (size_t) -1)
    return NULL;
  buf = xrealloc (buf, (size + 1) * sizeof (wchar_t));
  return buf;
}

Function: size_t wcstombs (char *string, const wchar_t wstring, size_t size)
The wcstombs ("wide character string to multibyte string") function converts the null-terminated wide character array wstring into a string containing multibyte characters, storing not more than size bytes starting at string, followed by a terminating null character if there is room. The conversion of characters begins in the initial shift state.

The terminating null character counts towards the size, so if size is less than or equal to the number of bytes needed in wstring, no terminating null character is stored.

If a code that does not correspond to a valid multibyte character is found, this function returns a value of -1. Otherwise, the return value is the number of bytes stored in the array string. This number does not include the terminating null character, which is present if the number is less than size.


Go to the first, previous, next, last section, table of contents.