Conversion of QString/string to char */const char * and use it in system()

I always learn some small tricks which are simple but sometime time taking to crack it. So, I always decided to write a blog post on my understandings and tricks which will help people like me in future.

Problem Statement: Need to run an executable file/commands e.g “DIR” command (command line input: Any Folder Path ) from a parent cpp module “sysOut.cpp” using “system()” function. For example, I want to run the following command from my parent cpp module.

system("dir samples\task");

So, I want to take “folder path” as command line argument like, > sysOut.exe samples/task (Using Backslash ‘/’ in windows also, for details, please refer my previous POST (http://blog.devgeek.co/2011/05/system-not-recognizing-path-with-using/) which explained the reason of why using it) We will also use ‘QString’ or ‘string’ for doing some string operations and using that into our program too.

SOLUTION:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* Program: sysOut.cpp */
#include 
#include ;
using namespace std;
 
int main(int argc, char **argv){
 char* pathName = argv[1];
 char exec[50];
 
 cout << "Input Path Name: " << pathName << endl;
 
 sprintf(exec, "dir %s", pathName); cout << "********Exec Line: " << exec << endl << endl;
 
 system(exec);
 
 return 0;
}

You will notice one thing that I am using sprintf for writing into formatted string, so that value of fileName is present in the ‘exec’ char string. If we do use ‘sprintf’ then system will consider fileName as the original Argument instead of the Path assigned to it.

Another Solution: using QString/string conversion to char */const char *

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* Program: sysOut.cpp */
#include 
#include 
using namespace std;
 
int main(){
 string fileName;
 fileName="blabla.txt";
 const char * fpPtr = fileName.data(); char exec[50];
 
 sprintf(exec, "parseOld.exe %s", fpPtr); cout << "Exec String: " << exec << endl;
 
 system(exec);
 
 return 0;
}

You will notice in this module that there is ‘blabla.txt‘ file is been saved into ‘string’. You need to convert ‘string’ to ‘char */const char *’ to make is usable for ‘sprintf‘.

So, we save convert the string into ‘const char *’ using string::data function declared in string library. It returns ‘const char *‘. So, we will save the returned data to const char * fpPtr variable as shown in the program.

And when you compile the modules, it will give back the result as expected. You may also refer a nice post on a Forum asked by some person: C++, system(), and variables. Hope this may help you. Thank you.

Animated Social Media Icons Powered by Acurax Wordpress Development Company