Search code examples
c++filesystem

How can I invoke the System() function inside a function in my c++ code?


I'm coming to invoke then function every thing goes well

int status = system("./my_exe_file input output");

But when i wanted to invoke it inside a function, i've got a little problem manipulating files:

void call(std::string f){
  FILE *in = fopen (in, "r");  
  int status = system("./my_exe_file f output");   
}

Can any one tell me what to do?


Solution

  • It's not possible to concatenate strings by simply write their variable name inside a string literal, like you did.

    To concatenate 2 or more strings, you can use the +/+= operator of std::string.

    std::string command = std::string("./my_exe_file ") + f + " output";
    system( command.c_str() );
    

    Note that the first literal "./my_exe_file " has to be encapsulated in a string, since you can add string literals to strings, and strings to strings, but not a string to a string literal.

    Note also, that in the second line the system() call wants a C string (char*). std::string::c_str() gives you the C string representation of the std::string.