Chapter Contents

Previous

Next
mbtowc

mbtowc



Convert a Multibyte Character to a Wide Character

Portability: ISO/ANSI C conforming


SYNOPSIS
DESCRIPTION
RETURN VALUE
CAUTIONS
EXAMPLE


SYNOPSIS

#include <stdlib.h>

int mbtowc(wchar_t *pwc, const char *s, size_t n);


DESCRIPTION

mbtowc determines how many bytes are needed to represent the multibyte character pointed to by s . If s is not NULL , mbtowc then stores the corresponding wide character in the array pointed to by pwc .

n specifies the maximum number of bytes to examine in the array pointed to by pwc .


RETURN VALUE

If s is not NULL , the return value is as follows:
0 is returned if s points to the null character.
length of the multibyte character is returned if the next n or fewer bytes constitute a valid multibyte character.
-1 is returned if the next n or fewer bytes do not constitute a valid multibyte character.

If s is NULL , the return value is as follows:
nonzero value is returned if the current locale supports state-dependent encodings.
0 is returned if the current locale does not support state-dependent encodings.


CAUTIONS

A diagnostic is not issued if mbtowc encounters invalid data; a return value of -1 is the only indication of an error.


EXAMPLE

This example finds a multibyte character in a mixed DBCS string using mbtowc .

#include <locale.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
   /* "begstr" points to the beginning of a DBCS MIXED string.  */
   /*  "mbc_sought" is the character value we're looking for.   */
int mbfind(char *begstr, wchar_t int mbc_sought)
{
   int mbclen;        /* length (in bytes) of current character */
   wchar_t mbc;       /* value of current character             */
   char *strptr;      /* pointer to current location in string  */
   strptr = begstr;

      /* Inform library that we will be accepting a DBCS string.*/
      /* That is, SO and SI are not regular control characters: */
      /* they indicate a change in shift state.                 */
   setlocale(LC_ALL, "dbcs");

      /* Reset to initial shift state. (A valid mixed string    */
      /* must begin in initial shift state).                    */
   mbtowc((wchar_t *)NULL, NULL, 0);

      /* One loop iteration per character. Advance "strptr" by  */
      /* number of bytes consumed.                              */
   while (mbclen = mbtowc(&mbc, strptr, MB_LEN_MAX)) {
      if (mbclen < 0) {
         fputs("Invalid pure DBCS string\n", stderr);
         abort();
      }
      if (mbc == mbc_sought)
         break;
      strptr += mbclen;
   }

      /* Last character was not '\0' -- must have found it     */
   if (mbclen) {
      printf("MBFIND: found at byte offset %d\n", strptr - begstr);
      return 1;
   }
   else {
      puts("MBFIND: character not found\n");
      return 0;
   }
}


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.