2
0

wcrtomb.c 813 B

123456789101112131415161718192021222324252627282930
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <wchar.h>
  4. #include <stdlib.h>
  5. #include "test_helpers.h"
  6. int main(void) {
  7. mbstate_t state;
  8. memset(&state, 0, sizeof state);
  9. wchar_t in[] = L"zß水🍌"; // or "z\u00df\u6c34\U0001F34C"
  10. size_t in_sz = sizeof in / sizeof *in;
  11. printf("Processing %zu wchar_t units: [ ", in_sz);
  12. for(size_t n = 0; n < in_sz; ++n) printf("%#x ", (unsigned int)in[n]);
  13. puts("]");
  14. char out[MB_CUR_MAX * in_sz];
  15. char *p = out;
  16. for(size_t n = 0; n < in_sz; ++n) {
  17. int rc = wcrtomb(p, in[n], &state);
  18. if(rc == -1) break;
  19. p += rc;
  20. }
  21. size_t out_sz = p - out;
  22. printf("into %zu UTF-8 code units: [ ", out_sz);
  23. for(size_t x = 0; x < out_sz; ++x) printf("%#x ", +(unsigned char)out[x]);
  24. puts("]");
  25. }