picolisp

Unnamed repository; edit this file to name it for gitweb.
git clone https://logand.com/git/picolisp.git/
Log | Files | Refs | README | LICENSE

lat1.c (1823B)


      1 /* lat1.c
      2  * 31mar05abu
      3  * Convert stdin (UTF-8, 2-Byte) to process or file (ISO-8859-15)
      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 // lat1 [-<cmd> [<arg> ..]]
     14 // lat1 [[+]<Outfile/ISO-8859-15>]
     15 int main(int ac, char *av[]) {
     16 	int c;
     17    pid_t pid = 0;
     18    FILE *fp = stdout;
     19 
     20    if (ac > 1) {
     21       char *mode = "w";
     22 
     23       if (*av[1] == '-') {
     24          int pfd[2];
     25 
     26          if (pipe(pfd) < 0) {
     27             fprintf(stderr, "lat1: Pipe error\n");
     28             return 1;
     29          }
     30          if ((pid = fork()) == 0) {
     31             close(pfd[1]);
     32             if (pfd[0] != STDIN_FILENO)
     33                dup2(pfd[0], STDIN_FILENO),  close(pfd[0]);
     34             execvp(av[1]+1, av+1);
     35          }
     36          if (pid < 0) {
     37             fprintf(stderr, "lat1: Fork error\n");
     38             return 1;
     39          }
     40          close(pfd[0]);
     41          if (!(fp = fdopen(pfd[1], mode))) {
     42             fprintf(stderr, "lat1: Pipe open error\n");
     43             return 1;
     44          }
     45       }
     46       else {
     47          if (*av[1] == '+')
     48             mode = "a",  ++av[1];
     49          if (!(fp = fopen(av[1], mode))) {
     50             fprintf(stderr, "lat1: '%s' open error\n", av[1]);
     51             return 1;
     52          }
     53       }
     54    }
     55 	while ((c = getchar_unlocked()) != EOF) {
     56       if ((c & 0x80) == 0)
     57          putc_unlocked(c,fp);
     58       else if ((c & 0x20) == 0)
     59          putc_unlocked((c & 0x1F) << 6 | getchar_unlocked() & 0x3F, fp);
     60       else {
     61          getchar_unlocked(); // 0x82
     62          getchar_unlocked(); // 0xAC
     63          putc_unlocked(0xA4, fp);
     64       }
     65 	}
     66    if (pid) {
     67       fclose(fp);
     68       while (waitpid(pid, NULL, 0) < 0)
     69          if (errno != EINTR) {
     70             fprintf(stderr, "lat1: Pipe close error\n");
     71             return 1;
     72          }
     73    }
     74    return 0;
     75 }