liveBook · Manning

Mbsrtowcs

As explained in Modern C, Third Edition

mbsrtowcs is a C standard-library function that converts a multibyte string to a wide character string while maintaining conversion state.

mbsrtowcs converts a multibyte string (MBS) into a null-terminated wide character string (WCS). Each wchar_t represents one character of the extended character set, while mbstate_t preserves conversion state across calls. section 14.3

 size_t mbsrtowcs(wchar_t*restrict dst, char const**restrict src,
                  size_t len, mbstate_t*restrict ps);

The declaration exposes the conversion interface: destination storage, a source pointer that can advance, a destination limit, and conversion state. section 14.3

Counting converted characters

mbsrlen uses mbsrtowcs(nullptr, &s, 0, &st) to determine the required wide-character length without writing a destination string. It copies or selects conversion state first, then treats an invalid source as an error condition. section 14.3

Allocating a converted string

mbsrdup first obtains the converted length, allocates space for mblen + 1 wchar_t elements, and calls mbsrtowcs to produce the wide string when allocation succeeds.

TAKEAWAY:

  • Preserve compatible mbstate_t state when conversion may continue across calls. section 14.3
  • Check for invalid source data; the conversion may set errno. section 14.3

How Modern C, Third Edition covers it

How deep it goes
Explains the interface, state handling, length-query idiom, allocation pattern, and invalid-source handling without detailing implementation internals.
Examples
Demonstrates zero-length counting through mbsrlen and allocated conversion through mbsrdup.
What it assumes
Assumes familiarity with C strings, pointers, allocation, wchar_t, and mbstate_t while defining MBS-to-WCS terminology.
What you can do after
Build converted wide strings and determine their required length while preserving conversion state.
How it connects
Connects multibyte strings with wide character strings, wchar_t, mbstate_t, and errno.

Also explained in

Compare how 2 books explain mbsrtowcs →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.