I don’t like re-inventing the wheel.
Is there a standard or Linux specific function to transform a C style string (char*)
to a char** style array of strings format like that passed into main?
i.e. given:
const char* s = "-n file -m -o output"
Dynamically convert that to what would be:
char** args = { "-n", "file", "-m", "-o", "output", 0 };
A function like:
char** build_arg_array(const char* cmd_line);
EDIT:
Thanks for the responses. Looks like there isn’t a one step function that does the above already.
On Unix-like systems, it is the shell that does the argument parsing. So your shell will apply all of its argument splitting, wildcard expansion, quoting, and redirection logic, generate the array of arguments, fork a new process, and call
execve(or one of the otherexecvariants) with the results of its parsing.So no, there isn’t a standard library call to parse arguments the way that the shell does, as that logic is implemented in the shell, not in the standard library. You can call
systemorpopen, which are wrappers aroundforkandexecto run a shell command with a string, or you could call out to the shell yourself usingforkandexec.Of course, then you have all of the problems of passing potentially untrusted input to a shell, and you would have to devise a way of communicating the results back to your parent process, perhaps using
popento open a pipe to read the results of the command you launch, which prints null-delimited arguments to standard out.Other than that, if you don’t want to spawn a new process and just want to parse the arguments within your program, you will have to implement your own parser.