1

I'm getting the comand from keyboard in a vector<string> and I want to use in execl(), but execl() takes a const char *. Is there another function similar to execl I can use that takes char* parameters, or how can I call execl with my char*?

void Process::exec(string & program, vector<string> & params){
int i;
char x=program[0];
if(x=='/'){
    char * argq[params.size()];
        for(i=0;i<params.size();i++){
            argq[i]=(string_to_c_convert(params[i]));
        }

    if(params.size()==2){
        execl(argq[0],argq[0],(char *)0);
    }
    if(params.size()==3){
        execl(argq[0],argq[1],argq[2],(char *)0);
    }
}
Tas
  • 7,023
  • 3
  • 36
  • 51
  • 1
    Use execv which was created for exactly this reason? – user253751 Nov 12 '15 at 02:12
  • I'm by no means an expert, and basically just looked up documentation (which may not even be official) but it _appears_ that [`execv` takes a `const char*`](http://linux.die.net/man/3/execv) as well. – Tas Nov 12 '15 at 02:14
  • @Tas it takes a pointer to an array of them. Am I understanding correctly that your problem is you want to be able to pass any number of parameters without copy-pasting code (to call `execl` with different numbers of parameters)? – user253751 Nov 12 '15 at 02:23
  • but i need use absolute path – Marcos Pinho Nov 12 '15 at 02:25
  • @Marcos.p well then `execv` sounds like exactly what you're looking for. You can have an array whose size is the number of parameters (in fact you already have that) and you can pass that to `execv` the same way, no matter how many parameters there are. – user253751 Nov 12 '15 at 02:49

2 Answers2

2

const char * doesn't mean that the argument must be const, it means it can be const.

There is no problem here to solve.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

You could make a std::string out of your char[] and then use std::string::data() which returns a const char*:

char * argq[params.size()];
    for(i=0;i<params.size();i++){
        argq[i]=(string_to_c_convert(params[i]));
    }

const std::string args(argq);
execl(args.data()[0], args.data()[1], 0);

Seeing as you already have a std::vector<std::string>, where I assume each std::string is actually just a single character (based on your loop and string_to_c_convert function), you could skip the char[] altogether and do the following:

execl(params[0].c_str(), params[1].c_str(), 0);
Tas
  • 7,023
  • 3
  • 36
  • 51