#define _XOPEN_SOURCE
#include <getopt.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include "misc.h"
NORETURN void usage(int exit_status)
{
printf(
"NAME\n"
" %s - wcswidth(3) wrapper\n"
"\n"
"SYNOPSIS\n"
" %s [OPTIONS] STRING\n"
"\n"
"DESCRIPTION\n"
" Output the number of columns needed to display STRING.\n"
"\n"
"OPTIONS\n"
" -h\n"
" Print this help message and exit.\n"
"\n"
" -v\n"
" Print the version and exit.\n"
"\n",
PROG_NAME, PROG_NAME);
exit(exit_status);
}
int main(int argc, char **argv)
{
signals_nointerrupt();
for (int opt; (opt = getopt(argc, argv, "hv")) != -1;)
{
switch (opt)
{
case 'h':
usage(EXIT_SUCCESS);
break;
case 'v':
puts(PROG_VERSION);
exit(EXIT_SUCCESS);
default:
exit(EXIT_FAILURE);
}
}
if (argc - optind != 1)
{
usage(EXIT_FAILURE);
}
setlocale(LC_ALL, "");
size_t arglen = strlen(argv[optind]) + 1;
wchar_t *wcs = xmalloc(arglen * sizeof(wchar_t));
size_t wcslen = mbstowcs(wcs, argv[optind], arglen);
if (wcslen == (size_t)-1)
{
die("mbstowcs: invalid multibyte sequence encountered");
}
printf("%d\n", wcswidth(wcs, wcslen));
free(wcs);
return EXIT_SUCCESS;
}