mbstouwcs.c 1.2 KB

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