Skip to content

Instantly share code, notes, and snippets.

@MaskRay
Created March 12, 2016 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaskRay/8042e39dc822a57c217f to your computer and use it in GitHub Desktop.
Save MaskRay/8042e39dc822a57c217f to your computer and use it in GitHub Desktop.
wcwidth: determine columns needed for a wide character
#ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
#endif
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
int main(int argc, char *argv[])
{
setlocale(LC_ALL, "");
mbstate_t ps;
const char *argv1 = argv[1];
int n = strlen(argv1);
wchar_t *wargv = (wchar_t *)malloc(sizeof(wchar_t)*n);
memset(&ps, 0, sizeof ps);
size_t g = mbsrtowcs(wargv, &argv1, n, &ps);
if (g == (size_t)-1)
fprintf(stderr, "invalid multibyte sequence has been encountered\n");
else
for (int i = 0; i < g; i++)
printf("%lc: %d\n", wargv[i], wcwidth(wargv[i]));
free(wargv);
return 0;
}
@MaskRay
Copy link
Author

MaskRay commented Mar 12, 2016

cc a.c -o a
./a $'\U1f632中a0 x'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment