myiconv.c 1.1 KB

1234567891011121314151617181920212223
  1. /* This scratch-program is to show how a possible computation of the output buffer left bytes to
  2. * the iconv function parameter fits in a context where the input is obtained
  3. * from other C Library functions. */
  4. #include <iconv.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. int main(int argc, char **argv) {
  8. iconv_t cd = iconv_open("UTF-16", "UTF-8");
  9. FILE *myutf8= fopen("myutf8.txt", "rb"); // actual decoding is performed beside the input stream, of which FILE be ratherly treated as bynary, according to what GNU C Library recomends with regard to portability, for which the "b" in "rb" stands. (rarely meaningful, yet docummented in fopen's manpage)
  10. char buf[1000];
  11. size_t bytes = fread(buf, 1, 1000, myutf8);
  12. size_t left = 2+bytes*2; // edge case every utf8_char is one-byte lengthed, and 2-bytes for a initial UTF-16 mark
  13. char *obuf = malloc(left), *inbuf = buf, *outbuf = obuf;
  14. size_t conv = iconv(cd, &inbuf, &bytes, &outbuf, &left);
  15. FILE *myutf16 = fopen("myutf16.txt", "wb");
  16. fwrite(obuf, 1, outbuf-obuf, myutf16);
  17. fclose(myutf16);
  18. fclose(myutf8);
  19. iconv_close(cd);
  20. exit(EXIT_SUCCESS);
  21. return 0;
  22. }