tsticonv.cc
1 /*
2  * Compile as:
3 *
4  * g++ tsticonv.cc `pkg-config --cflags --libs glibmm-2.4`
5 *
6 * /
7 
8 #include <iostream>
9 #include <cstdlib>
10 #include <iomanip>
11 #include <locale>
12 #include <glibmm/convert.h>
13 #include <cerrno>
14 #include <cstring>
15 //#include <iconv.h>
16 
17 int main()
18 {
19  setlocale(LC_ALL, "");
20 
21  char buf[256];
22 
23  size_t inbytes = 0;
24  for (int i = 1; i < 256; ++i)
25  buf[inbytes++] = i;
26 
27  Glib::IConv iconv("UTF8", "ISO8859-1");
28 #if 0
29  iconv_t cd = iconv_open("UTF8", "ISO8859-1");
30  if (cd == (iconv_t)-1)
31  {
32  perror("iconv_open");
33  exit(1);
34  }
35 #endif
36 
37  char buf2[512];
38  size_t outbytes = sizeof(buf2);
39  char* inbuf = buf;
40  char* outbuf = buf2;
41 
42  while(inbytes > 0)
43  {
44  size_t res = iconv.iconv(&inbuf,& inbytes,& outbuf,& outbytes);
45  if (res == static_cast<size_t>(-1))
46  {
47  std::cerr << "iconv: " << std::strerror(errno) << std::endl;
48  exit(1);
49  }
50  else
51  std::cout << "res = " << res << "; inbytes = " << inbytes << "; outbytes = " << outbytes << '\n';
52  }
53 
54  //iconv_close(cd);
55 
56  std::cout << "outbytes = " << outbytes << '\n';
57  for (int i = 0; i < sizeof(buf2) - outbytes; ++i)
58  {
59  unsigned int data = (unsigned int)(unsigned char)buf2[i];
60  std::cout << i << " : " << data;
61  if (data == 194 || data == 195)
62  {
63  ++i;
64  std::cout << " " << (unsigned int)(unsigned char)buf2[i];
65  }
66  std::cout << '\n';
67  }
68 
69  std::string s(buf2, sizeof(buf2) - outbytes);
70  std::cout << "Output : \"" << s << "\"\n";
71 
72  char const* charset;
73  bool is_utf8 = g_get_charset(&charset);
74  std::cout << "g_get_charset() = " << charset << std::endl;
75 
76  if (!is_utf8)
77  {
78  std::cout << "charset is not \"UTF-8\", fix that.\n";
79  exit(1);
80  }
81 
82  Glib::ustring str(s);
83  std::cout << "strlen = " << str.length() << '\n';
84 
85  std::cout << "Glib::ustring: \"" << str << "\"\n";
86 
87  std::cout << "Printable characters:\n";
88  Glib::ustring output;
89  for (Glib::ustring::iterator iter = str.begin(); iter != str.end(); ++iter)
90  {
91  Glib::ustring::iterator::value_type c =* iter;
92  if (g_unichar_isprint(c))
93  {
94  output += c;
95  std::cout << c << '\n';
96  }
97  else
98  output += '?';
99  }
100  std::cout << "Printable characters: \"" << output << "\"\n";
101 }

Copyright © 2006 - 2010 Carlo Wood.  All rights reserved.