Skip to content

Instantly share code, notes, and snippets.

@andreubotella
Created April 18, 2022 12:23
Show Gist options
  • Save andreubotella/01e77a5ba3021c4a0515999e87fa21a7 to your computer and use it in GitHub Desktop.
Save andreubotella/01e77a5ba3021c4a0515999e87fa21a7 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <wordexp.h>
using namespace std;
char hexDigit(int digit) {
if (digit >= 0 && digit <= 9) {
return '0' + digit;
} else if (digit >= 10 && digit <= 15) {
return 'A' + digit - 10;
} else {
return '?';
}
}
void printString(char *str) {
std::cout << "\"";
for (;; str++) {
char c = *str;
if (c == '\0') {
break;
} else if (c == '"') {
std::cout << "\\\"";
} else if (c == '\n') {
std::cout << "\\n";
} else if (c == '\r') {
std::cout << "\\r";
} else if (c == '\\') {
std::cout << "\\\\";
} else if (c < 0x20) {
char hex[3] = {hexDigit(c / 16), hexDigit(c % 16), '\0'};
std::cout << "\\x" << hex;
} else {
char cstr[2] = {c, '\0'};
std::cout << cstr;
}
}
std::cout << "\"";
}
int main(int argc, char **argv) {
if (argc != 2) {
std::cerr << "Argc (" << argc << ") != 2" << std::endl;
return -1;
}
wordexp_t exp;
int error = wordexp(argv[1], &exp, 0);
if (error != 0) {
const char *error_name;
if (error == WRDE_BADCHAR) {
error_name = "WRDE_BADCHAR";
} else if (error == WRDE_BADVAL) {
error_name = "WRDE_BADVAL";
} else if (error == WRDE_CMDSUB) {
error_name = "WRDE_CMDSUB";
} else if (error == WRDE_NOSPACE) {
error_name = "WRDE_NOSPACE";
} else if (error == WRDE_SYNTAX) {
error_name = "WRDE_SYNTAX";
} else {
error_name = "?????";
}
std::cerr << "wordexp error code " << error << " (" << error_name << ")"
<< std::endl;
return error;
}
if (exp.we_offs != 0) {
std::cerr << "Unexpected initial offsets." << std::endl;
return -1;
}
std::cout << "[";
for (size_t i = 0; i < exp.we_wordc; i++) {
if (i != 0) {
std::cout << ", ";
}
printString(exp.we_wordv[i]);
}
std::cout << "]" << std::endl;
wordfree(&exp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment