mplisp

miniPicoLisp with FFI and modules for Buddy BDD library, OpenGL, Gtk and GMP
git clone https://logand.com/git/mplisp.git/
Log | Files | Refs

utf2.c (1682B)


      1 /* utf2.c
      2  * 31mar05abu
      3  * Convert process or file (ISO-8859-15) to stdout (UTF-8, 2-Byte)
      4  */
      5 
      6 #include <stdio.h>
      7 #include <stdlib.h>
      8 #include <unistd.h>
      9 #include <errno.h>
     10 #include <signal.h>
     11 #include <sys/wait.h>
     12 
     13 // utf2 [-<cmd> [<arg> ..]]
     14 // utf2 [<Infile/ISO-8859-15>]
     15 int main(int ac, char *av[]) {
     16 	int c;
     17    pid_t pid = 0;
     18    FILE *fp = stdin;
     19 
     20    if (ac > 1) {
     21       if (*av[1] == '-') {
     22          int pfd[2];
     23 
     24          if (pipe(pfd) < 0) {
     25             fprintf(stderr, "utf2: Pipe error\n");
     26             return 1;
     27          }
     28          if ((pid = fork()) == 0) {
     29             close(pfd[0]);
     30             if (pfd[1] != STDOUT_FILENO)
     31                dup2(pfd[1], STDOUT_FILENO),  close(pfd[1]);
     32             execvp(av[1]+1, av+1);
     33          }
     34          if (pid < 0) {
     35             fprintf(stderr, "utf2: Fork error\n");
     36             return 1;
     37          }
     38          close(pfd[1]);
     39          if (!(fp = fdopen(pfd[0], "r"))) {
     40             fprintf(stderr, "utf2: Pipe open error\n");
     41             return 1;
     42          }
     43       }
     44       else if (!(fp = fopen(av[1], "r"))) {
     45          fprintf(stderr, "utf2: '%s' open error\n", av[1]);
     46          return 1;
     47       }
     48    }
     49 	while ((c = getc_unlocked(fp)) != EOF) {
     50       if (c == 0xA4)
     51          putchar_unlocked(0xE2), putchar_unlocked(0x82), putchar_unlocked(0xAC);
     52       else if (c >= 0x80) {
     53          putchar_unlocked(0xC0 | c>>6 & 0x1F);
     54          putchar_unlocked(0x80 | c & 0x3F);
     55       }
     56       else
     57          putchar_unlocked(c);
     58 	}
     59    if (pid) {
     60       fclose(fp);
     61       while (waitpid(pid, NULL, 0) < 0)
     62          if (errno != EINTR) {
     63             fprintf(stderr, "utf2: Pipe close error\n");
     64             return 1;
     65          }
     66    }
     67    return 0;
     68 }