diff --git a/src/fetch.h b/src/fetch.h index 268a050..b46843e 100644 --- a/src/fetch.h +++ b/src/fetch.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -194,36 +195,20 @@ class Command static char **split(string cmd) { - vector v; + vector v = {}; - string token; - for (char c : cmd) + istringstream ss{cmd}; + for (string arg{}; getline(ss, arg, ' '); ) { - if (c == ' ') - { - v.push_back(token); - token = ""; - continue; - } - token += c; + if (arg != "") + v.push_back(arg); } - v.push_back(token); - char **argv = (char **)calloc( - v.size() + 1, - sizeof(char *)); // +1 for the terminating NULL pointer - if (argv == NULL) - { - throw runtime_error("calloc failed"); - } + char **argv = new char*[v.size() + 1]; // +1 for the terminating NULL pointer char **p = argv; - for (string s : v) + for (auto &s : v) { - if ((*p = strdup(s.c_str())) == NULL) - { - throw runtime_error("strdup failed"); - } - p++; + *p++ = std::strcpy(new char[s.length() + 1], s.c_str()); } *p = (char *)0; // terminated by a NULL pointer diff --git a/src/test.cpp b/src/test.cpp index f272d3c..9f17dbb 100644 --- a/src/test.cpp +++ b/src/test.cpp @@ -65,6 +65,9 @@ static void test_Command() expect(1, c->getOutputLines(), "getOutputLines()"s); expect("akamoku\n"s, c->getErrorOutput(), "getErrorOutput()"s); + c = Command::exec("ls ../README.md"s); + expect("../README.md\n"s, c->getOutput(), "argc = 2"s); + c = Command::exec("false"s); expect(1, c->getExitCode(), "Exit code"s);