Barney Chambers
Barney Chambers

Reputation: 2783

variables in system() call C++

I have a variable in argv[1] which I need to call inside another c++ file in such a way:

        system("./assemblerL.out", argv[1]);

this above is incorrect syntax as I am getting "too many arguments" errors.

What is the correct way of doing this?

Upvotes: 5

Views: 11841

Answers (3)

kfsone
kfsone

Reputation: 24249

std::system only takes one parameter, which must be the complete string you want to execute. Be aware that, if this is Linux, the result is achieved by invoking a sub-shell, so expansion/substitution may occur. You may want to consider the exec line of functions. For Windows, you may want to investigate CreateProcess.

You have several choices for building your command line:

// c-like
char buffer[1024];
snprintf(buffer, sizeof(buffer), "%s %s", "command", "argument");
system(buffer); // could be truncated

// c++ string based
std::string commandline = std::string(command) + std::string(argument);
system(commandline.c_str());

// stringbuffer
#include <sstream>
std::ostringstream buf;
buf << command << " " << argument;
system(buf.str().c_str());

Upvotes: 1

deviantfan
deviantfan

Reputation: 11414

system can take only one parameter, and that´s a whole line like entered in the shell
(well, not with everything a shell like Bash got, but that doesn´t matter here).

With C++, just use std::string to concat the parts:

system((std::string("./assemblerL.out ") + argv[1]).c_str());  

Or, more readable:

std::string line = "./assemblerL.out ";
line += argv[1];
system(line.c_str());  

Remember to make sure that argv[1] exists before using it.

Upvotes: 8

Sourav Kanta
Sourav Kanta

Reputation: 2757

Try concatinating the command into a single string and then call system like :

char ch[50]="";
strcat(ch,"./assemblerL.out ");
strcat(ch,argv[1]);
system(ch); 

Upvotes: 1

Related Questions