C mbstowcs() function

C mbstowcs() function - Convert a character string to a wide-character string

Syntax mbstowcs() function

size_t mbstowcs(schar_t *pwcs, const char *str, size_t n)

The mbstowcs() function is used to get the length of the sequence of the multibyte characters pointed to by string. Afterwards, it converts the multibyte character string that begins in the initial shift state into a wide character string. Wide characters are stored in the buffer pointed to by pwcs. A maximum of n wide characters are written.

Parameters mbstowcs() function

Name Description Required /Optional
pwcs The address of a sequence of wide characters. Required
str The address of a sequence of null terminated multibyte characters. Required
n This is the maximum number of wchar_t characters to be interpreted. Required

Return value from mbstowcs()

  • The number of wide characters generated, excluding any null wide characters at the end.
  • The function returns (size_t)-1 if a multibyte character is encountered that is not valid.

Example: mbstowcs() function

The following example compiled with LOCALETYPE(*LOCALE) and * SYSIFCOPT(*IFSIO).

/* Source:https://www.ibm.com/docs */
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <errno.h>
#include <string.h>

#define  LOCNAME     "qsys.lib/JA_JP.locale"
#define  LOCNAME_EN  "qsys.lib/EN_US.locale"

int main(void)
    int length, sl = 0;
    char  string[10];
    char  string2[] = "ABC";
    wchar_t buffer[10];
    memset(string, '\0', 10);
    string[0] = 0xC1;
    string[1] = 0x0E;
    string[2] = 0x41;
    string[3] = 0x71;
    string[4] = 0x41;
    string[5] = 0x72;
    string[6] = 0x0F;
    string[7] = 0xC2;
    /* In this first example we will convert                  */
    /* a multibyte character when the CCSID of locale         */
    /* associated with LC_CTYPE is 37.                        */

    if (setlocale(LC_ALL, LOCNAME_EN) == NULL)
        printf("setlocale failed.\n");

    length = mbstowcs(buffer, string2, 10);

    /* In this case length ABC is converted to             */
    /* 0x00C100C200C3.  Length will be 3.                  */

    printf("length = %d\n\n", length);

    /* Now lets try a multibyte example.  We first must set the *
    /* locale to a multibyte locale.  We choose a locale with
    /* CCSID 5026  */

    if (setlocale(LC_ALL, LOCNAME) == NULL)
        printf("setlocale failed.\n");

    length = mbstowcs(buffer, string, 10);

    /* The buffer now has the value:                           */
    /* 0x00C14171417200C2        length is 4                   */

    printf("length = %d\n\n", length);



setlocale failed.
length = 3

setlocale failed.
length = 8

C Programming Code Editor:

Previous C Programming: C mblen()
Next C Programming: C mbtowc()

Follow us on Facebook and Twitter for latest update.