~q3cpma/misc-tools

ref: 0695c6188d0f70c89d8e1757f2463b2e3869a60a misc-tools/wcswidth.c -rw-r--r-- 1.3 KiB
0695c618q3cpma htmldecode: move to root, use genhtab instead of lex 1 year, 4 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#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;
}