The wcsrtombs()
function translates a wide-character string to its equivalent multibyte sequence that begins in the conversion state. It does this until it translates maximum bytes or encounters the NULL
character.
The wcsrtombs()
function is defined in the following library:
#include<stdlib.h>
The following is the declaration of wcsrtombs()
function:
size_t wcstombs (char* destination, const wchar_t* source, size_t maximum, mbstate_t* state);
destination
: The pointer to a char
array at least maximum bytes long.source
: The pointer to the wide-character string being translated.maximum
: An unsigned integral which specifies the maximum number of bytes being translated.state
: The pointer to the conversion state object.On successful conversion, the function returns the number of bytes written into destination, excluding the NULL
character. In case of any error, the function returns -1.
The code below explains the use of wcsrtombs()
function.
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <wchar.h>int main() {const wchar_t* wstr = L"C language is amazing :)";printf("Wide-character string: %ls\n", wstr); //prints the wide character stringmbstate_t state; //declaring mbstate_t objectmemset(&state, 0, sizeof state);int returnValue;char dest[32];returnValue = wcsrtombs(dest, &wstr, sizeof(dest), &state);printf("Multibyte string: %s\n", dest);printf("Number of bytes converted: %d\n", returnValue);return 0;}
In line 7 and line 8, wide-character string wstr
is defined and printed. In line 10, state
variable is declared as an mbstate_t. Then, in line 15, wcsrtombs()
function is called with the necessary parameters and values are printed in the following two lines.
Free Resources