CKTIS / C
mbrtowc — C23 restartable multibyte conversion
`mbrtowc(pwc, s, n, ps)` from `<wchar.h>` examines at most `n` bytes of the next multibyte character in the current execution encoding. When a valid character is completed, it returns the number of bytes that completed it and stores the corresponding `wchar_t` if `pwc != NULL`; the `mbstate_t` at `ps` carries a character across buffer boundaries.
Version: C23
Syntax
size_t mbrtowc(wchar_t * restrict pwc, const char * restrict s, size_t n, mbstate_t * restrict ps);mbrtowc(pwc, s, n, ps) from <wchar.h> examines at most n bytes of the next multibyte character in the current execution encoding. When a valid character is completed, it returns the number of bytes that completed it and stores the corresponding wchar_t if pwc != NULL; the mbstate_t at ps carries a character across buffer boundaries.
The example selects the guaranteed "C" locale, zero-initializes explicit state, and really converts the one-byte "A". Output 1 0041 1 confirms one consumed byte, the wide-character value, and a return to initial state as reported by mbsinit.
A result of 0 denotes the null wide character and initial state, (size_t)-2 an incomplete but potentially valid character with no store, and (size_t)-1 an encoding error with errno == EILSEQ, no store, and unspecified state. After -2, supply following bytes with the same ps; after -1, do not continue without reinitializing. s == NULL is exactly equivalent to mbrtowc(NULL, "", 1, ps), ps == NULL selects internal state not required to avoid data races, and wchar_t need not be a Unicode code point. When s == NULL, the caller-supplied pwc and n values are ignored.
Examples
#include <locale.h>
#include <stdio.h>
#include <wchar.h>
int main(void){setlocale(LC_CTYPE,"C");mbstate_t state={0};wchar_t wc=0;size_t n=mbrtowc(&wc,"A",1,&state);printf("%zu %04lX %d\n",n,(unsigned long)wc,mbsinit(&state)!=0);return 0;}
Result
1 0041 1
The example selects the guaranteed `"C"` locale, zero-initializes explicit state, and really converts the one-byte `"A"`. Output `1 0041 1` confirms one consumed byte, the wide-character value, and a return to initial state as reported by `mbsinit`.