1 /* iconv.c - Convert character encoding
3 * Copyright 2014 Felix Janda <felix.janda@posteo.de>
5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/iconv.html
7 * Deviations from posix: no idea how to implement -l
9 USE_ICONV(NEWTOY(iconv, "cst:f:", TOYFLAG_USR|TOYFLAG_BIN))
14 depends on TOYBOX_ICONV
16 usage: iconv [-f FROM] [-t TO] [FILE...]
18 Convert character encoding of files.
21 -f convert from (default utf8)
22 -t convert to (default utf8)
36 static void do_iconv(int fd, char *name)
38 char *outstart = toybuf+2048;
39 size_t outlen, inlen = 0;
43 char *in = toybuf, *out = outstart;
45 if (readlen && 0>(readlen = read(fd, in+inlen, 2048-inlen))) {
46 perror_msg("read '%s'", name);
53 iconv(TT.ic, &in, &inlen, &out, &outlen);
55 // Skip first byte of illegal sequence to avoid endless loops
56 if (toys.optflags & FLAG_c) in++;
57 else *(out++) = *(in++);
60 if (out != outstart) xwrite(1, outstart, out-outstart);
61 memmove(toybuf, in, inlen);
67 if (!TT.to) TT.to = "utf8";
68 if (!TT.from) TT.from = "utf8";
70 if ((iconv_t)-1 == (TT.ic = iconv_open(TT.to, TT.from)))
71 perror_exit("%s/%s", TT.to, TT.from);
72 loopfiles(toys.optargs, do_iconv);
73 if (CFG_TOYBOX_FREE) iconv_close(TT.ic);