在 system() 函数中使用变量 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4907805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using variables in system() function c++
提问by martin
string line;
ifstream myfile ("aaa.txt");
getline (myfile,line);
system("curl.exe -b cookie.txt -d test="+line+" http://example.com");
And It doesn't work! I also tried line.c_str(); But it didnt work either. Please help me.
它不起作用!我也试过 line.c_str(); 但它也没有工作。请帮我。
回答by Skurmedel
Problem 1:
问题1:
Your problem stems from the fact that system
is of signature:
您的问题源于system
具有签名的事实:
int system (const char *command);
What you have is of type std::string
.
你所拥有的是类型std::string
。
One way to fix this is to build a new std::string
and then get the char pointer using c_str()
.
解决此问题的一种方法是构建一个新的std::string
,然后使用c_str()
.
string cmd("curl.exe -b cookie.txt -d test=");
cmd += line;
cmd += " http://example.com";
Then pass the content to system
.
然后将内容传递给system
.
system(cmd.c_str());
Problem 2:
问题2:
Reading data and passing it unvalidated and unclean to system
will allow anyone using your program to run commands at the shell.
读取数据并将其传递给未经验证且不干净的数据,system
将允许任何使用您的程序的人在 shell 上运行命令。
This is a security risk.
这是一个安全风险。
回答by Sergei Tachenov
It doesn't work because you're passing a C++ string to a C function system(). c_str() can help, but you should apply it to the whole string:
它不起作用,因为您将 C++ 字符串传递给 C 函数 system()。c_str() 可以提供帮助,但您应该将其应用于整个字符串:
system(("curl.exe -b cookie.txt -d test="+line+" http://example.com").c_str());
As noted in the comments below, passing random variables to system() can be quite dangerous, so you should only do that if you know exactly what it may contain. If it's supplied by the user or received from the network, you probably shouldn't do that. Pass the string through some sort of "escape" function or use spawn()/exec()/whatever else that doesn't pass it to the shell.
正如下面的评论中所指出的,将随机变量传递给 system() 可能非常危险,因此只有在您确切知道它可能包含的内容时才应该这样做。如果它是由用户提供或从网络接收的,您可能不应该这样做。通过某种“转义”函数传递字符串或使用 spawn()/exec()/任何其他不将其传递给 shell 的方法。
回答by Xeo
Build the string you're passing to system()
with a 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());
}