charset_utils.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. FTP file system
  3. Copyright (C) 2007 Robson Braga Araujo <robsonbraga@gmail.com>
  4. This program can be distributed under the terms of the GNU GPL.
  5. See the file COPYING.
  6. */
  7. #include "config.h"
  8. #include <string.h>
  9. #include <limits.h>
  10. #include <iconv.h>
  11. #include <errno.h>
  12. #include <stdlib.h>
  13. #include "ftpfs.h"
  14. int convert_charsets(const char* from, const char* to, char** str) {
  15. iconv_t cd;
  16. char* s = *str;
  17. if (!s || !*s)
  18. return 0;
  19. if (to && from && (cd = iconv_open(to, from)) != (iconv_t)-1) {
  20. ICONV_CONST char* ib;
  21. char* buf;
  22. char* ob;
  23. size_t ibl, obl;
  24. ibl = strlen(s) + 1;
  25. ib = s;
  26. obl = MB_LEN_MAX * ibl;
  27. buf = (char*)malloc(obl * sizeof(char));
  28. ob = buf;
  29. do {
  30. if (iconv(cd, &ib, &ibl, &ob, &obl) == (size_t)-1) {
  31. DEBUG(2, "iconv return error %d\n", errno);
  32. if (obl) {
  33. *ob++ = *ib++;
  34. ibl--;
  35. obl--;
  36. }
  37. }
  38. } while (ibl && obl);
  39. *ob = 0;
  40. DEBUG(2, "iconv return %s\n", buf);
  41. iconv_close (cd);
  42. free(*str);
  43. *str = buf;
  44. } else {
  45. DEBUG(2, "iconv_open return error %d\n", errno);
  46. }
  47. return 0;
  48. }