Using variables in system() function c++

前端 未结 3 1241
慢半拍i
慢半拍i 2020-12-30 14:00


  string line;
  ifstream myfile (\"aaa.txt\");
  getline (myfile,line);
  system(\"curl.exe -b cookie.txt -d test=\"+line+\"  

        
相关标签:
3条回答
  • 2020-12-30 14:12

    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.

    0 讨论(0)
  • 2020-12-30 14:25

    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());
    }
    
    0 讨论(0)
  • 2020-12-30 14:35

    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.

    0 讨论(0)
提交回复
热议问题