Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables in system() function c++


  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.

like image 645
martin Avatar asked Feb 05 '11 15:02

martin


2 Answers

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.

like image 95
Sergei Tachenov Avatar answered Oct 14 '22 11:10

Sergei Tachenov


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.

like image 37
Skurmedel Avatar answered Oct 14 '22 12:10

Skurmedel