about iconv

I want to use iconv.h to convert some text to another charset.

The code is below:

#include <stdio.h>
#include <stdlib.h>
#include <iconv.h>

int main()
{
        iconv_t cd;
        char instr[]="";
        char *inbuf;
        char *outbuf;
        unsigned int insize=7;
        unsigned int avail=10;
        unsigned int nconv;

        inbuf=instr;
        outbuf=malloc(10);

        cd=iconv_open("gbk","utf-8");
        if(cd==(iconv_t)-1)
        {
                printf("fail.\n");
        }
        nconv=iconv(cd,&inbuf,&insize,&outbuf,&avail);

        outbuf[5]='\0';
        printf("%s\n",outbuf);
        printf("nconv is: %d",nconv);

        return 0;
}

But after all things is done the buffer area "outbuf" is still empty.It
doesn't output anything.Could someone give me some help?

Thanks.

The offset of outbuf after iconv() will be advanced, so you need to do some pointer arithmetic to go back by the number of advanced output bytes, or maintain another pointer to the output buffer before iconv() and use that.

For example, this works on my system:

#include <stdio.h>
#include <stdlib.h>
#include <iconv.h>

int main()
{
        iconv_t cd;
        char instr[]="";
        char *inbuf;
        char *outbuf;
        unsigned int insize = strlen(instr);
		unsigned int outbufsize = 10;
        unsigned int avail = outbufsize;
        unsigned int nconv;

        inbuf=instr;
        outbuf=(char*)malloc(outbufsize);
		memset(outbuf, '\0', outbufsize);

        cd=iconv_open("GB2312", "UTF-8");
        if(cd==(iconv_t)-1)
        {
                printf("fail.\n");
        }
        nconv=iconv(cd,&inbuf,&insize,&outbuf,&avail);
		outbuf -= (outbufsize-avail);

        printf("%s\n", outbuf);
        printf("nconv is: %d\n", nconv);
		free(outbuf);

        return 0;
}

Seems like the return value of iconv() is not too meaningful except for checking error condition. Most programs I have seen using iconv() just throw it away.

I modified my code like yours and it begins to work now.

Thanks a lot!

My modified code is pasted below: :smiley:

#include <stdio.h>
#include <stdlib.h>
#include <iconv.h>
#include <string.h>

int main()
{
        iconv_t cd;
        char instr[]="";
        char *inbuf;
        char *outbuf;
        char *outptr;
        unsigned int insize=strlen(instr);
	unsigned int outputbufsize=10;
        unsigned int avail=outputbufsize;
        unsigned int nconv;

        inbuf=instr;
        outbuf=(char *)malloc(outputbufsize);
	outptr=outbuf;
	memset(outbuf,'\0',outputbufsize);

        cd=iconv_open("gbk","utf-8");
        if(cd==(iconv_t)-1)
        {
                printf("fail.\n");
        }
        nconv=iconv(cd,&inbuf,&insize,&outptr,&avail);

        //outbuf[5]='\0';
        printf("%s\n",outbuf);
        printf("%s\n","aa");

        return 0;
}

You don't need this, because memset at the beginning will fill the malloc()ed buffer with \0 bytes.

Thanks :smiley: