Site Tools


h-wchar

Table of Contents

<wchar.h>

<wchar.h> provides wide-character functions (C95): wprintf, wcslen, wcscmp, etc. The encoding of wchar_t is platform-dependent (UTF-32 on Linux, UTF-16 on Windows), making portable Unicode code difficult.

For portable Unicode, prefer <uchar.h> with char32_t (UTF-32) or char16_t (UTF-16).

Example

This example demonstrates wide-string handling and locale-aware output.

// compile: gcc -o wcharexample wcharexample.c
// run: ./wcharexample
// description: wide string handling and character counting
 
#include <wchar.h>
#include <locale.h>
#include <string.h>
#include <stdio.h>
 
int main() {
    setlocale(LC_ALL, "");
 
    const wchar_t* ws = L"héllo";
    const char* ns = "héllo";
 
    wprintf(L"wide string: %ls\n", ws);
    wprintf(L"wcslen: %zu (wchar units)\n", wcslen(ws));
    printf("strlen: %zu (bytes)\n", strlen(ns));
    printf("sizeof(wchar_t): %zu\n", sizeof(wchar_t));
 
    return 0;
}

Common functions

String length and comparison:

  • wcslen(s): length of wide string
  • wcscmp(s1, s2): compare wide strings
  • wcsncmp(s1, s2, n): compare first n wide characters
  • wcscoll(s1, s2): compare with locale
  • wcsxfrm(d, s, n): transform for sorting

String copying and concatenation:

  • wcscpy(d, s): copy wide string
  • wcsncpy(d, s, n): copy up to n characters
  • wcscat(d, s): append wide string
  • wcsncat(d, s, n): append up to n characters

String searching:

  • wcschr(s, c): find wide character in string
  • wcsrchr(s, c): find last occurrence
  • wcspbrk(s, accept): find first of accept chars
  • wcsspn(s, accept): length of prefix in accept
  • wcscspn(s, reject): length of prefix not in reject
  • wcsstr(s, sub): find substring

Output/input:

  • wprintf(fmt, ...): wide character formatted print
  • fwprintf(f, fmt, ...): wide printf to file
  • wscanf(fmt, ...): wide scanf
  • fwscanf(f, fmt, ...): wide scanf from file
h-wchar.md · Last modified: by 127.0.0.1