Example (iconv -- Convert Characters to New Code Set)

This example converts an array of characters coded in encoded character set IBM-850 (in in) to an array of characters coded in encoded character set IBM-037 (stored in out).

#include <iconv.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
   const char fromcode[] = "IBM-850";
   const char tocode[] = "IBM-037";
   iconv_t    cd;
   char       in[] = "ABCDEabcde";
   size_t     in_size;
   char       *inptr = in;
   char       out[100];
   size_t     out_size = sizeof(out);
   char       *outptr = out;
   int        i;
   if ((iconv_t)(-1) == (cd = iconv_open(tocode, fromcode))) {
      printf("Failed to iconv_open %s to %s.\n", fromcode, tocode);
      exit(EXIT_FAILURE);
   }
   /* Convert the first 3 characters in array "in". */
   in_size = 3;
   if ((size_t)(-1) == iconv(cd, &inptr, &in_size, &outptr, &out_size)) {
      printf("Fail to convert first 3 characters to new code set.\n");
      exit(EXIT_FAILURE);
   }
   /* Convert the rest of the characters in array "in". */
   in_size = sizeof(in) - 3;
   if ((size_t)(-1) == iconv(cd, &inptr, &in_size, &outptr, &out_size)) {
      printf("Fail to convert the rest of the characters to new code set.\n");
      exit(EXIT_FAILURE);
   }
   *outptr = '\0';
   printf("The hex representation of string %s are:\n  In codepage %s ==> ",
          in, fromcode);
   for (i = 0; in[i] != '\0'; i++) {
      printf("0x%02x ", in[i]);
   }
   printf("\n  In codepage %s ==> ", tocode);
   for (i = 0; out[i] != '\0'; i++) {
      printf("0x%02x ", out[i]);
   }
   if (-1 == iconv_close(cd)) {
      printf("Fail to iconv_close.\n");
      exit(EXIT_FAILURE);
   }
   return 0;
   /****************************************************************************
      The output should be similar to :
      The hex representation of string ABCDEabcde are:
        In codepage IBM-850 ==> 0x41 0x42 0x43 0x44 0x45 0x61 0x62 0x63 0x64 0x65
        In codepage IBM-037 ==> 0xc1 0xc2 0xc3 0xc4 0xc5 0x81 0x82 0x83 0x84 0x85
   ****************************************************************************/
}