Simple iconv (libiconv) example

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

#include <iostream>
#include <fstream>
#include <iconv.h>

int main(int argc, char *argv[])
{
	char src[] = "abcčde";
	char dst[100];
	size_t srclen = 6;
	size_t dstlen = 12;

	fprintf(stderr,"in: %s\n",src);

	char * pIn = src;
	char * pOut = ( char*)dst;

	iconv_t conv = iconv_open("UTF-8","CP1250");
	iconv(conv, &pIn, &srclen, &pOut, &dstlen);
	iconv_close(conv);

	fprintf(stderr,"out: %s\n",dst);
}

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/