what is the correct way to concat strings in c++ and execute using system

310 views Asked by At

The following code is used in a native c++ library to create directory under android shell,

JNIEXPORT void JNICALL Java_com_xprea_lib_STB_mkdir(JNIEnv* env, jobject javaThis, jstring jdir) {
const char* dir = (env)->GetStringUTFChars(jdir, 0);    
string d=dir;
string cmd= "su -c 'mkdir -p "+d+"'";
const char* c=cmd.c_str();
LOGE("s%s",c);
system(c);

}

it's not working because the command is built from concatenated strings. I tested it without concatenation and it's working

What is the correct way to concat the strings all together and send them to system()

2

There are 2 answers

3
Oncaphillis On

Your concatenation "su -c 'mkdir -p "+d+"'" results in the string

su -c 'mkdir -p BLA' (If the dir name is BLA)

So the command su searches for a command named mkdir -p BLA which it won't find. Better make:

"su -c mkdir -p '"+d+"'" your concatenation. This way it will search for a command named mkdir which it hopefully will find, and the directory name may even contain white space (although you would have to escape the ' and \ character with \.

6
mystic_coder On

Replace these 3 lines :

string d=dir;
string cmd= "su -c 'mkdir -p "+d+"'";
const char* c=cmd.c_str();

With these lines :

char cmd[1024];
sprintf(cmd,"su -c 'mkdir -p %s '",dir);