txt2Cstring

Command for converting text to C string notation \n for new line, hexadecimal notation for non printable characters
git clone https://noulin.net/git/txt2Cstring.git
Log | Files | Refs

commit e9a2383ffcb6086aae58bf877834b98c2e66bcbc
parent f9a13241b19c38c909100f3d9e739cf8ffc29930
Author: Remy Noulin <loader2x@gmail.com>
Date:   Wed, 23 Mar 2022 16:44:25 -0400

convert non printable characters to hexidecimal notation, add support for stdin stream

txt2Cstring.c | 68 +++++++++++++++++++++++++++++++++++++++++++++++++----------
1 file changed, 57 insertions(+), 11 deletions(-)

Diffstat:
Mtxt2Cstring.c | 68+++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
1 file changed, 57 insertions(+), 11 deletions(-)

diff --git a/txt2Cstring.c b/txt2Cstring.c @@ -6,33 +6,79 @@ int argc; char **argv; -/* enable/disable logging */ -/* #undef pLog */ -/* #define pLog(...) */ - int main(int ARGC, char** ARGV) { argc = ARGC; argv = ARGV; initLibsheepy(ARGV[0]); - setLogMode(LOG_VERBOSE); + + cleanSmallArrayP(lines) = null; if (argc < 2) { - logXFailure("Filename missing"); - } + char *s = null; + // no arguments + // check stdin + + // read all the data from stdin to s + fd_set readfds; + FD_ZERO(&readfds); + FD_SET(STDIN_FILENO, &readfds); - if (not isPath(argv[1])) { - logXFailure(formatS("File "BLD RED UDL "'%s'"RST" not found ", argv[1])); + struct timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 1000; + + int chr; + + int sel_rv = select(1, &readfds, NULL, NULL, &timeout); + if (sel_rv > 0) { + while ((chr = getchar()) != EOF) pErrorNULL(appendG(&s,chr)); + } else if (sel_rv == -1) { + perror("select failed"); + } + + if (isEmptyG(s)) { + logW("Empty string."); + XSUCCESS; + } + cleanSmallString(S); + setValG(&S, s); + lines = splitG(&S, '\n'); } + else { + if (not isPath(argv[1])) { + logXFailure(formatS("File "BLD RED UDL "'%s'"RST" not found ", argv[1])); + } - createAllocateSmallArray(lines); - readFileG(lines, argv[1]); + lines = allocG(rtSmallArrayt); + readFileG(lines, argv[1]); + } iter(lines, L) { castS(l,L); // replace '\' with '\\' replaceG(l, "\\", "\\\\", 0); replaceG(l, "\"", "\\\"", 0); + replaceG(l, "\r", "\\r", 0); + replaceG(l, "\t", "\\t", 0); + replaceG(l, "\a", "\\a", 0); + replaceG(l, "\b", "\\b", 0); + replaceG(l, "\v", "\\v", 0); + replaceG(l, "\f", "\\f", 0); + // print non printable characters as hexadecimal "\xNN" + cleanCharP(s) = malloc(4*lenG(l)+1); + char *t = s; + char *in = getValG(l); + range(i, lenG(l)) { + if (isprint(in[i])) + *(t++) = in[i]; + else { + sprintf(t, "\\x%02X", (u8)in[i]); + t += 4; + } + } + *t = 0; + setValG(l, s); prependG(l, "\""); appendG(l, "\\n\""); setPG(lines, iterIndexG(lines), l);