Truncating a string in C
This version uses the proper APIs to work with the locale's multibyte encoding (with single-byte encodings being a trivial case of multibyte). It will fail if it encounters an invalid byte sequence (e.g. byte > 127 in the "C" locale), though it could be changed to treat each rejected byte as a single character.
#include <locale.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> int main(int argc, char **argv) { size_t n = 12, totlen = 0, maxlen, chlen; setlocale(LC_ALL, ""); if (argc != 2) return EXIT_FAILURE; maxlen = strlen(argv[1]); while (n--) { chlen = mbrlen(argv[1] + totlen, maxlen - totlen, NULL); if (chlen > MB_CUR_MAX) return EXIT_FAILURE; totlen += chlen; } printf("%.*s\n", (int)totlen, argv[1]); return 0; }