C programming stdlib.h function - size_t mbstowcs(schar_t *pwcs, const char *str, size_t n)

www.igift‮di‬ea.com

The mbstowcs function is defined in the stdlib.h header file in C programming language. This function is used to convert a multibyte string (a character string that uses more than one byte to represent each character) into a wide character string.

The function signature is as follows:

size_t mbstowcs(wchar_t *dest, const char *src, size_t n);

Here, dest is a pointer to the destination wide character string, src is a pointer to the source multibyte string, and n is the maximum number of wide characters to be written to the destination buffer.

The mbstowcs function returns the number of wide characters written to the destination buffer, not including the terminating null character. If an invalid multibyte character is encountered, the function returns (size_t)-1.

For example, the following code converts a multibyte string to a wide character string:

#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>

int main() {
    const char* mbstr = "Hello, world!";
    size_t dest_size = mbstowcs(NULL, mbstr, 0) + 1;
    wchar_t* wcstr = malloc(dest_size * sizeof(wchar_t));
    mbstowcs(wcstr, mbstr, dest_size);
    wprintf(L"%ls\n", wcstr);
    free(wcstr);
    return 0;
}

In this example, the mbstr variable contains a multibyte string, and the dest_size variable is first calculated by calling mbstowcs with a null pointer for the destination buffer and a size of 0. This tells the function to just return the required size for the destination buffer. The dest_size variable is then used to allocate memory for the wide character string, and the mbstowcs function is called again to actually perform the conversion. Finally, the resulting wide character string is printed using the wprintf function, and the allocated memory is freed using the free function.