mbstouwcs.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include <stdbool.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <wchar.h>
  5. /* Do not include the above headers in the example.
  6. */
  7. wchar_t *
  8. mbstouwcs (const char *s)
  9. {
  10. /* Include the null terminator in the conversion. */
  11. size_t len = strlen (s) + 1;
  12. wchar_t *result = reallocarray (NULL, len, sizeof (wchar_t));
  13. if (result == NULL)
  14. return NULL;
  15. wchar_t *wcp = result;
  16. mbstate_t state;
  17. memset (&state, '\0', sizeof (state));
  18. while (true)
  19. {
  20. wchar_t wc;
  21. size_t nbytes = mbrtowc (&wc, s, len, &state);
  22. if (nbytes == 0)
  23. {
  24. /* Terminate the result string. */
  25. *wcp = L'\0';
  26. break;
  27. }
  28. else if (nbytes == (size_t) -2)
  29. {
  30. /* Truncated input string. */
  31. errno = EILSEQ;
  32. free (result);
  33. return NULL;
  34. }
  35. else if (nbytes == (size_t) -1)
  36. {
  37. /* Some other error (including EILSEQ). */
  38. free (result);
  39. return NULL;
  40. }
  41. else
  42. {
  43. /* A character was converted. */
  44. *wcp++ = towupper (wc);
  45. len -= nbytes;
  46. s += nbytes;
  47. }
  48. }
  49. return result;
  50. }