main.cxx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. extern "C" {
  2. #include <iconv.h>
  3. }
  4. #include <array>
  5. #include <cstddef>
  6. #include <cstdlib>
  7. #include <iostream>
  8. #include <string>
  9. #include <system_error>
  10. class iconv_desc
  11. {
  12. private:
  13. iconv_t iconvd_;
  14. public:
  15. iconv_desc(const std::string& tocode, const std::string& fromcode)
  16. {
  17. iconvd_ = iconv_open(tocode.c_str(), fromcode.c_str());
  18. if (iconvd_ == reinterpret_cast<iconv_t>(-1))
  19. throw std::system_error(errno, std::system_category());
  20. }
  21. ~iconv_desc() { iconv_close(iconvd_); }
  22. operator iconv_t() { return this->iconvd_; }
  23. };
  24. int main()
  25. {
  26. try {
  27. auto conv_d = iconv_desc{ "ISO-8859-1", "UTF-8" };
  28. auto from_str = std::array<char, 10>{ u8"a\xC3\xA4o\xC3\xB6u\xC3\xBC" };
  29. auto to_str = std::array<char, 7>{};
  30. auto from_str_ptr = from_str.data();
  31. auto from_len = from_str.size();
  32. auto to_str_ptr = to_str.data();
  33. auto to_len = to_str.size();
  34. const auto iconv_ret =
  35. iconv(conv_d, &from_str_ptr, &from_len, &to_str_ptr, &to_len);
  36. if (iconv_ret == static_cast<std::size_t>(-1))
  37. throw std::system_error(errno, std::system_category());
  38. std::cout << '\'' << from_str.data() << "\' converted to \'"
  39. << to_str.data() << '\'' << std::endl;
  40. return EXIT_SUCCESS;
  41. } catch (const std::system_error& ex) {
  42. std::cerr << "ERROR: " << ex.code() << '\n'
  43. << ex.code().message() << std::endl;
  44. }
  45. return EXIT_FAILURE;
  46. }