Developer Blog - Inventic.eu
  • Skipper - The ORM Designer
  • VsBuilds - Parallel building
  • Pulpo - Free Skipper CLI

Tag: #libiconv

Simple iconv (libiconv) example

Here is a simple example how to use the iconv library.

#include &lt;iostream&gt;<br />
#include &lt;fstream&gt;<br />
#include &lt;iconv.h&gt;</p>
<p>int main(int argc, char *argv[])<br />
{<br />
	char src[] = &quot;abcčde&quot;;<br />
	char dst[100];<br />
	size_t srclen = 6;<br />
	size_t dstlen = 12;</p>
<p>	fprintf(stderr,&quot;in: %s\n&quot;,src);</p>
<p>	char * pIn = src;<br />
	char * pOut = ( char*)dst;</p>
<p>	iconv_t conv = iconv_open(&quot;UTF-8&quot;,&quot;CP1250&quot;);<br />
	iconv(conv, &amp;pIn, &amp;srclen, &amp;pOut, &amp;dstlen);<br />
	iconv_close(conv);</p>
<p>	fprintf(stderr,&quot;out: %s\n&quot;,dst);<br />
}<br />

During my attempts with libiconv library I encountered two different problems:

Converting function returns 0, but pOut is empty

This is because iconv function modify pOut ptr during string processing. When you need to access output buffer after **iconv()** function finish its work, you have to access it via different pointer than one passed to this function. In my code I'm using *dst and pOut ptrs;

Conversion between different character sets returns strange results

Check if have correct order of parameters in your **iconv_open()** and **iconv()** function. Function **iconv_open()** has as its first parameter OUTPUT encoding, and as second parameter INPUT encoding. While **iconv()** function has as first parameters INPUT variables, and as second parameters OUTPUT variables. This inconsistency is really confusing.

Notes

Official libiconv site: http://www.gnu.org/software/libiconv/

Official libiconv documentation: http://www.gnu.org/software/libiconv/documentation/libiconv-1.13/

08 Nov 2010

Posted by: ludek.vodicka

Programming #C++ #libiconv