【问题标题】:Using argument char argv[] in system()在 system() 中使用参数 char argv[]
【发布时间】:2012-05-27 07:58:05
【问题描述】:

我需要从我的 c++ 代码中执行一个 perl 脚本。这是通过 system() 完成的。
现在我需要从我的代码中传递第二个参数:

int main(int argc, char * argv[])

像这样进入我的系统():

char *toCall="perl test.pl "+argv[1];
system(toCall);

现在它带来了错误:“‘const char [14]’和‘char**’类型的无效操作数到二进制‘operator+’”

我做错了什么?

【问题讨论】:

  • 您的代码完全不安全;如果 argv[1] 是 ; /bin/rm -rf $HOME
  • @BasileStarynkevitch:你是对的,但我们不知道 OP 是否计划添加一些输入检查;在这里展示它不会使问题更清楚。

标签: c++ arguments command-line-arguments


【解决方案1】:

您不能通过分配char* 创建连接字符串。您需要使用std::stringstd::ostringstream

std::ostringstream s;

s << "perl test.pl";
for (int i = 1; i < argc; i++)
{
    // Space to separate arguments.
    // You need to quote the arguments if
    // they can contain spaces.
    s << " " << argv[i];
}

system(s.str().c_str());

【讨论】:

    【解决方案2】:

    使用std::string,点赞

    std::string const command = std::string( "perl test.pl " ) + argv[1];
    system( command.c_str() );
    

    您不能添加两个原始指针。

    但是std::string 提供了+ 运算符的重载。

    【讨论】:

    • 技术上第一个是const char[],但实际上它确实归结为它试图从中添加衰减的指针。
    • 这会造成一个安全漏洞:./script 'myarg &amp;&amp; echo hello' 将使用 myarg 执行 ./script 并打印 hello。
    猜你喜欢
    • 2010-10-21
    • 2011-01-29
    • 2011-07-08
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 2015-01-28
    • 2012-06-16
    相关资源
    最近更新 更多