txt2Cstring

Log

Files

Refs

txt2Cstring.c (2006B)

     1 #! /usr/bin/env sheepy
     2 /* or direct path to sheepy: #! /usr/local/bin/sheepy */
     3 
     4 /* Libsheepy documentation: https://spartatek.se/libsheepy/ */
     5 #include "libsheepyObject.h"
     6 
     7 int argc; char **argv;
     8 
     9 int main(int ARGC, char** ARGV) {
    10 
    11   argc = ARGC; argv = ARGV;
    12 
    13   initLibsheepy(ARGV[0]);
    14 
    15   cleanSmallArrayP(lines) = null;
    16 
    17   if (argc < 2) {
    18     char *s = null;
    19     // no arguments
    20     // check stdin
    21 
    22     // read all the data from stdin to s
    23     fd_set readfds;
    24     FD_ZERO(&readfds);
    25     FD_SET(STDIN_FILENO, &readfds);
    26 
    27     struct timeval timeout;
    28     timeout.tv_sec = 0;
    29     timeout.tv_usec = 1000;
    30 
    31     int chr;
    32 
    33     int sel_rv = select(1, &readfds, NULL, NULL, &timeout);
    34     if (sel_rv > 0) {
    35       while ((chr = getchar()) != EOF) pErrorNULL(appendG(&s,chr));
    36     } else if (sel_rv == -1) {
    37       perror("select failed");
    38     }
    39 
    40     if (isEmptyG(s)) {
    41       logW("Empty string.");
    42       XSUCCESS;
    43     }
    44     cleanSmallString(S);
    45     setValG(&S, s);
    46     lines = splitG(&S, '\n');
    47   }
    48   else {
    49     if (not isPath(argv[1])) {
    50       logXFailure(formatS("File "BLD RED UDL "'%s'"RST" not found ", argv[1]));
    51     }
    52 
    53     lines = allocG(rtSmallArrayt);
    54     readFileG(lines, argv[1]);
    55   }
    56 
    57   iter(lines, L) {
    58     castS(l,L);
    59     // replace '\' with '\\'
    60     replaceG(l, "\\", "\\\\", 0);
    61     replaceG(l, "\"", "\\\"", 0);
    62     replaceG(l, "\r", "\\r", 0);
    63     replaceG(l, "\t", "\\t", 0);
    64     replaceG(l, "\a", "\\a", 0);
    65     replaceG(l, "\b", "\\b", 0);
    66     replaceG(l, "\v", "\\v", 0);
    67     replaceG(l, "\f", "\\f", 0);
    68     // print non printable characters as hexadecimal "\xNN"
    69     cleanCharP(s) = malloc(4*lenG(l)+1);
    70     char *t       = s;
    71     char *in      = getValG(l);
    72     range(i, lenG(l)) {
    73       if (isprint(in[i]))
    74         *(t++) = in[i];
    75       else {
    76         sprintf(t, "\\x%02X", (u8)in[i]);
    77         t += 4;
    78       }
    79     }
    80     *t = 0;
    81     setValG(l, s);
    82     prependG(l, "\"");
    83     appendG(l, "\\n\"");
    84     setPG(lines, iterIndexG(lines), l);
    85   }
    86   logG(lines);
    87 }
    88 // vim: set expandtab ts=2 sw=2: