在system()函数c ++中使用变量

时间:2011-02-05 15:45:36

标签: windows curl system c++


  string line;
  ifstream myfile ("aaa.txt");
  getline (myfile,line);
  system("curl.exe -b cookie.txt -d test="+line+"  http://example.com");

它不起作用!我也试过line.c_str();但它也没有用。请帮帮我。

3 个答案:

答案 0 :(得分:11)

它不起作用,因为您将C ++字符串传递给C函数系统()。 c_str()可以提供帮助,但您应该将它应用于整个字符串:

system(("curl.exe -b cookie.txt -d test="+line+"  http://example.com").c_str());

如下面的评论中所述,将随机变量传递给system()可能非常危险,因此只有在确切知道它可能包含的内容时才应该这样做。如果它由用户提供或从网络接收,您可能不应该这样做。将字符串传递给某种“转义”函数或使用spawn()/ exec()/其他任何不传递给shell的函数。

答案 1 :(得分:10)

问题1:

您的问题源于system具有签名的事实:

int system (const char *command);

您所拥有的是std::string类型。

解决此问题的一种方法是构建新的std::string,然后使用c_str()获取char指针。

string cmd("curl.exe -b cookie.txt -d test=");
cmd += line;
cmd += "  http://example.com";

然后将内容传递给system

system(cmd.c_str());

问题2:

读取数据并将其传递给未经验证且不清洁的system将允许使用您的程序的任何人在shell上运行命令。

这是一种安全风险。

答案 2 :(得分:3)

使用stringstream构建您传递给system()的字符串!

#include <sstream>
#include <fstream>
#include <string>
using namespace std;

int main(void){
    string line;
    ifstream myfile("aaa.txt");
    getline(myfile,line);
    stringstream call_line;
    call_line << "curl.exe -b cookie.txt -d test=" << line << "  http://example.com");
    system(call_line.str().c_str());
}
相关问题