WCSWIDTH(3C) Standard C Library Functions WCSWIDTH(3C)

wcswidth, wcswidth_ldetermine number of columns for wide-character string

#include <wchar.h>

int
wcswidth(const wchar_t *str, size_t len);

#include <wchar.h>
#include <xlocale.h>

int
wcswidth_l(const wchar_t *str, size_t len, locale_t loc);

The () and wcswidth_l() functions count the total number of columns that are required to display the contents of the wide-character string str. For each wide-character in the string str, the equivalent of wcwidth(3C) is called and the result summed to a running total which is returned.

Up to len wide-characters from str will be evaluated; however, the functions will stop iterating if they encounter the null wide-character (L'\0').

The wide-characters in str must be valid characters in the current locale or in the case of the () function, the locale specified by loc. The functions will fail if any of the wide-characters in str are valid in the current locale, but considered non-printable (as in iswprint(3C) would fail for the character) or the wide-character does not represent a valid character in the locale.

Upon successful completion, the wcswidth() and wcswidth_l() functions return the total number of columns that are required to display the wide-character string. Otherwise, is returned to indicate that an invalid or non-printable wide-character was encountered.

Using the wcswidth() function to count characters in a string.

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

int
main(void)
{
        wchar_t *str = L"Hello world";
        int ret = wcswidth(str, wcslen(str));
        (void) printf("wcswidth returned: %d\n", ret);
        return (0);
}

When compiled and run, this program outputs:

$ gcc -Wall -Wextra example.c
$ ./a.out
wcswidth returned: 11

The () function is MT-Safe as long as the thread-specific or global locale is not changed while it is running.

The () function is MT-Safe as long as the locale loc is not freed while the function is running.

iswprint(3C), newlocale(3C), setlocale(3C), uselocale(3C), wcwidth(3C)

September 15, 2024 OmniOS