Skip to content

Instantly share code, notes, and snippets.

@countingpine
Last active April 25, 2020 13:09
Show Gist options
  • Save countingpine/7646c78e9458cbba128ce4a632e9980e to your computer and use it in GitHub Desktop.
Save countingpine/7646c78e9458cbba128ce4a632e9980e to your computer and use it in GitHub Desktop.
ascme.c - convert stdin to printable string with C/bash-style escape sequences
#include <stdio.h>
#define IN(a, z) (c >= (a) && c <= (z))
int main() {
int count=0;
int c;
while (!feof(stdin)) {
c = getc(stdin);
// EOF?
if (!IN(0, 255)) break;
// Backslash
if (c == '\\')
printf("\\\\");
// Printable char
else if (IN(32, 126))
printf("%c", c);
// Before printable range (including CR/LF/Tab)
else if (IN(0, 31))
printf("%c", c);
// Anything else (including UTF-8)
else
printf("\\x%02x", c);
count++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment