function
<cstdlib>

wcstombs

size_t wcstombs (char* dest, const wchar_t* src, size_t max);
Convert wide-character string to multibyte string
Translates wide characters from the sequence pointed by src to the multibyte equivalent sequence (which is stored at the array pointed by dest), up until either max bytes have been translated or until a wide characters translates into a null character.

If max bytes are successfully translated, the resulting string stored in dest is not null-terminated.

The resulting multibyte sequence begins in the initial shift state (if any).

The behavior of this function depends on the LC_CTYPE category of the selected C locale.

Parameters

dest
Pointer to an array of char elements long enough to contain the resulting sequence (at most, max bytes).
src
C wide string to be translated.
max
Maximum number of bytes to be written to dest.
size_t is an unsigned integral type.

Return Value

The number of bytes written to dest, not including the eventual ending null-character.
If a wide character that does not correspond to a valid multibyte character is encountered, a (size_t)-1 value is returned.
Notice that size_t is an unsigned integral type, and thus none of the values possibly returned is less than zero.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* wcstombs example */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* wcstombs, wchar_t(C) */

int main() {
  const wchar_t str[] = L"wcstombs example";
  char buffer[32];
  int ret;

  printf ("wchar_t string: %ls \n",str);

  ret = wcstombs ( buffer, str, sizeof(buffer) );
  if (ret==32) buffer[31]='\0';
  if (ret) printf ("multibyte string: %s \n",buffer);

  return 0;
}


Output:

wchar_t string: wcstombs example 
multibyte string:  wcstombs example 

Data races

The function accesses the array pointed by src, and modifies the array pointed by dest.
The function may also access and modify an internal state object, which may cause data races on concurrent calls to this function if the implementation uses a static object (see wcsrtombs for an alternative that can use an external state object).
Concurrently changing locale settings may also introduce data races.

Exceptions (C++)

No-throw guarantee: this function throws no exceptions.

If dest does not point to an array long enough to contain the translated sequence, or if src is either not null-terminated or does not contain enough wide characters to generate a sequence of max multibyte characters, it causes undefined behavior.

See also