1234567891011121314151617181920212223 |
- /* This scratch-program is to show how a possible computation of the output buffer left bytes to
- * the iconv function parameter fits in a context where the input is obtained
- * from other C Library functions. */
- #include <iconv.h>
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, char **argv) {
- iconv_t cd = iconv_open("UTF-16", "UTF-8");
- 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)
- char buf[1000];
- size_t bytes = fread(buf, 1, 1000, myutf8);
- size_t left = 2+bytes*2; // edge case every utf8_char is one-byte lengthed, and 2-bytes for a initial UTF-16 mark
- char *obuf = malloc(left), *inbuf = buf, *outbuf = obuf;
- size_t conv = iconv(cd, &inbuf, &bytes, &outbuf, &left);
- FILE *myutf16 = fopen("myutf16.txt", "wb");
- fwrite(obuf, 1, outbuf-obuf, myutf16);
- fclose(myutf16);
- fclose(myutf8);
- iconv_close(cd);
- exit(EXIT_SUCCESS);
- return 0;
- }
|