Guest User

Untitled

a guest
Jan 22nd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. #include <iconv.h>
  2.  
  3. #include <string>
  4.  
  5. int convert(string input, wstring &output)
  6. {
  7. char *inbuf, *iptr, *outbuf, *wptr;
  8. iconv_t cd;
  9. size_t nconv, inlen, avail;
  10.  
  11. cd = iconv_open("UCS-4-INTERNAL", "UTF-8");
  12. if (cd == (iconv_t)-1)
  13. {
  14. perror("iconv error");
  15. return -1;
  16. }
  17.  
  18. iptr = inbuf = strdup(input.c_str());
  19. inlen = input.size();
  20. avail = inlen * 4 + 1;
  21. wptr = outbuf = (char*)calloc(avail * sizeof(char), 1);
  22.  
  23. nconv = iconv(cd, &iptr, &inlen, &wptr, &avail);
  24. if (nconv == (size_t)-1)
  25. {
  26. perror("iconv error");
  27. free(inbuf);
  28. free(outbuf);
  29. return -1;
  30. }
  31.  
  32. iconv(cd, NULL, NULL, &wptr, &avail);
  33.  
  34. if (avail >= sizeof(char))
  35. {
  36. *wptr = '\0';
  37. }
  38. else
  39. {
  40. perror("iconv error");
  41. free(inbuf);
  42. free(outbuf);
  43. return -1;
  44. }
  45.  
  46. if (iconv_close(cd) != 0)
  47. {
  48. perror("iconv error");
  49. free(inbuf);
  50. free(outbuf);
  51. return -1;
  52. }
  53.  
  54. wchar_t *wstr = reinterpret_cast<wchar_t*>(outbuf);
  55. output = wstring(wstr);
  56. free(outbuf);
  57.  
  58. return 1;
  59. }
Add Comment
Please, Sign In to add comment