What is wcsrtombs() in C?

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.

Library

The wcsrtombs() function is defined in the following library:

#include<stdlib.h>

Declaration

The following is the declaration of wcsrtombs() function:

size_t wcstombs (char* destination, const wchar_t* source, size_t maximum, mbstate_t* state);

Parameters and return value

Parameters

  • 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.

Return value

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.

Code

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 string
mbstate_t state; //declaring mbstate_t object
memset(&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;
}

Explanation

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

Copyright ©2025 Educative, Inc. All rights reserved