在c ++中将字符串转换为argv [英] convert string to argv in c++
本文介绍了在c ++中将字符串转换为argv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个std ::字符串包含一个要执行execv的命令,什么是最好的C ++方式将其转换为execv()的第二个参数所需的char * argv []
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()?
澄清:
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);
推荐答案
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];
当然,这不适用于使用 rm file.mp3
。你可以考虑POSIX函数 wordexp
,它关心这些和更多。
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.
这篇关于在c ++中将字符串转换为argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文