Using variables in system() function c++

2019-03-21 10:55发布

问题:


  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.

回答1:

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:

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.



回答2:

Problem 1:

Your problem stems from the fact that system is of signature:

int system (const char *command);

What you have is of type std::string.

One way to fix this is to build a new std::string and then get the char pointer using c_str().

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

Then pass the content to system.

system(cmd.c_str());

Problem 2:

Reading data and passing it unvalidated and unclean to system will allow anyone using your program to run commands at the shell.

This is a security risk.



回答3:

Build the string you're passing to system() with a stringstream!

#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());
}