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

mar*_*tin 6 c++ windows curl system


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

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

Ser*_*nov 11

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

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

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


Sku*_*del 10

问题1:

你的问题源于system签名的事实:

int system (const char *command);
Run Code Online (Sandbox Code Playgroud)

你拥有的是什么类型std::string.

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

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

然后将内容传递给system.

system(cmd.c_str());
Run Code Online (Sandbox Code Playgroud)

问题2:

读取数据并将其传递为unvalidated和unclean system将允许任何使用您的程序的人在shell上运行命令.

这是一种安全风险.

  • @Xeo:是的,如果你将`foo&fire_nukes.exe&REM`传递给他的程序,它将运行curl.exe然后尝试运行fire_nukes.exe.在*nix上看起来会略有不同,但想法是一样的. (2认同)