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);

	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.


Official libiconv site:

Official libiconv documentation:


  1. I’ve been stuck on this problem for 8 hours now! And you’ve solved it for me thanks so much. I’ve pasted my code below which works nicely. Hope this also helps someone.

    Some of my code here:

    iconv_t xttx = iconv_open(“UTF-8″,”KOI8-R”);

    if (xttx == (iconv_t)-1){
    cout << "error\n";

    string de = loadFile("/tmp/russs");
    char *xs = (char *)malloc(de.length()+1);
    xs = strcpy(xs,de.c_str());

    size_t s1 = de.length(),s2 = de.length()*3;

    char *res = (char *)calloc(s2,1);

    char *lref = res;

    size_t rs;
    rs = iconv(xttx, &xs, &s1, &res, &s2);

    iconv_close (xttx);

    // PRINT lref NOT res

  2. I want to convert UTF-8 to Shift JIS but iconv_open and iconv gives Errno 95 (operation not supported) Can some help?

Leave a Reply

Your email address will not be published. Required fields are marked *