toybox/toys/posix/iconv.c
<<
>>
Prefs
   1/* iconv.c - Convert character encoding
   2 *
   3 * Copyright 2014 Felix Janda <felix.janda@posteo.de>
   4 *
   5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/iconv.html
   6 *
   7 * Deviations from posix: no idea how to implement -l
   8
   9USE_ICONV(NEWTOY(iconv, "cst:f:", TOYFLAG_USR|TOYFLAG_BIN))
  10
  11config ICONV
  12  bool "iconv"
  13  default y
  14  help
  15    usage: iconv [-f FROM] [-t TO] [FILE...]
  16
  17    Convert character encoding of files.
  18
  19    -c  Omit invalid chars
  20    -f  Convert from (default UTF-8)
  21    -t  Convert to   (default UTF-8)
  22*/
  23
  24#define FOR_iconv
  25#include "toys.h"
  26#include <iconv.h>
  27
  28GLOBALS(
  29  char *f, *t;
  30
  31  void *ic;
  32)
  33
  34static void do_iconv(int fd, char *name)
  35{
  36  char *outstart = toybuf+2048;
  37  size_t outlen, inlen = 0;
  38  int readlen = 1;
  39
  40  for (;;) {
  41    char *in = toybuf, *out = outstart;
  42
  43    if (readlen && 0>(readlen = read(fd, in+inlen, 2048-inlen))) {
  44      perror_msg("read '%s'", name);
  45      return;
  46    }
  47    inlen += readlen;
  48    if (!inlen) break;
  49
  50    outlen = 2048;
  51    iconv(TT.ic, &in, &inlen, &out, &outlen);
  52    if (in == toybuf) {
  53      // Skip first byte of illegal sequence to avoid endless loops
  54      if (toys.optflags & FLAG_c) in++;
  55      else *(out++) = *(in++);
  56      inlen--;
  57    }
  58    if (out != outstart) xwrite(1, outstart, out-outstart);
  59    memmove(toybuf, in, inlen);
  60  }
  61}
  62
  63void iconv_main(void)
  64{
  65  if (!TT.t) TT.t = "UTF-8";
  66  if (!TT.f) TT.f = "UTF-8";
  67
  68  if ((iconv_t)-1 == (TT.ic = iconv_open(TT.t, TT.f)))
  69    perror_exit("%s/%s", TT.t, TT.f);
  70  loopfiles(toys.optargs, do_iconv);
  71  if (CFG_TOYBOX_FREE) iconv_close(TT.ic);
  72}
  73