Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 468
aaronstacy Avatar asked Oct 02 '09 21:10

aaronstacy


People also ask

Is argv a string in C?

Argc and argv Argv looks weird, but what it is is an array of C-style strings. Sometimes you see it declared as "char *argv[]," which is equivalent to the above. Element argv[i] will be a c style string containing the i-th command line argument. These are defined from 0 through argc-1.

Is argv 1 a string?

argv is an array of strings, or say, an array of char * . So the type of argv[1] is char * , and the type of argv[1][0] is char . Save this answer.

Is argv always a string?

The second argument to main, usually called argv, is an array of strings. A string is just an array of characters, so argv is an array of arrays. There are standard C functions that manipulate strings, so it's not too important to understand the details of argv, as long as you see a few examples of using it.

What does * argv [] mean in C?

What is ARGV? As a concept, ARGV is a convention in programming that goes back (at least) to the C language. It refers to the “argument vector,” which is basically a variable that contains the arguments passed to a program through the command line.


1 Answers

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

like image 68
Andy Ross Avatar answered Oct 23 '22 02:10

Andy Ross