Search code examples
c++stringshellvectorposix

Turn std::string into array of char* const*'s


I am writing a command shell in C++ using the POSIX api, and have hit a snag. I am executing via execvp(3), so I somehow need to turn the std::string that contains the command into a suitable array of char* consts*'s that can be passed to:

int execvp(const char *file, char *const argv[]);

I have been racking my brain for hours but I can't think of any realistic or sane way to do this. Any help or insight on how I can achieve this conversion would be greatly appreciated. Thank you and have a good day!

edit: As per request of Chnossos, here is an example:

const char *args[] = {"echo", "Hello,", "world!"};
execvp(args[0], args);

Solution

  • Assuming you have a string that contains more than "one argument", you will first have to split the string (using a std::vector<std::string> would work to store the separate strings), then for each element in the vector, store the .c_str() of that string into a const char args[MAXARGS] [or a std::vector<const char*> args; and use args.data() if you don't mind using C++11]. Do not forget to store a 0 or nullptr in the last element.

    It is critical if you use c_str that the string you are basing that of is not a temporary: const char* x = str.substr(11, 33).c_str(); will not give you the thing you want, because at the end of that line, the temporary string is destroyed, and its storage freed.

    If you have only one actual argument,

    const char* args[2] = { str.c_str(), 0 }; 
    

    would work.