Search code examples
c++stdstringargv

convert string to argv in c++


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);

Solution

  • std::vector<char *> args;
    std::istringstream iss(cmd);
    
    std::string token;
    while(iss >> token) {
      char *arg = new char[token.size() + 1];
      copy(token.begin(), token.end(), arg);
      arg[token.size()] = '\0';
      args.push_back(arg);
    }
    args.push_back(0);
    
    // now exec with &args[0], and then:
    
    for(size_t i = 0; i < args.size(); i++)
      delete[] args[i];
    

    Of course, this won't work with commans that use quoting like rm "a file.mp3". You can consider the POSIX function wordexp which cares about that and much more.