Alex Rivera | Logout

convert string to argv in c++

Asked 2009-10-02T21:10:28.373
11

I have an std::string containing a command to be executed with execv, what is the best "C++" way to convert it to the "char *argv[]" that is required by the second parameter of execv()?

To clarify:

std::string cmd = "mycommand arg1 arg2";
char *cmd_argv[];

StrToArgv(cmd, cmd_argv); // how do I write this function?

execv(cmd_argv[0], cmd_argv);
Edit
Report

2 Answers

11

Very non-unixy answers here. What's wrong with:

std::string cmd = "echo hello world";
execl("/bin/sh", "/bin/sh", "-c", cmd.c_str(), NULL);

Why bother writing a command line parser when there's a perfectly good one already on the system?

(Note: one good reason is because you don't trust the string you're about to execute. One hopes that this is already true, but the shell will do "more" with that string than a naive whitespace-splitter will and thus open more security holes if you aren't careful.)

answered 2009-10-02T21:23:39.267
1

This is a variation on litb's answer, but without all the manual memory allocation. It still won't handle quoting.

#include <vector>
#include <string>
#include <sstream>

std::string cmd = "mycommand arg1 arg2";
std::istringstream ss(cmd);
std::string arg;
std::list<std::string> ls;
std::vector<char*> v;
while (ss >> arg)
{
   ls.push_back(arg); 
   v.push_back(const_cast<char*>(ls.back().c_str()));
}
v.push_back(0);  // need terminating null pointer

execv(v[0], &v[0]);

I feel kind of dirty about the const_cast<>, but programs really shouldn't be modifying the contents of the argv strings.

answered 2009-10-03T01:24:31.773

Your Answer