system() not recognizing path (with \\) using g++ complier for windows

I was using system() function

"int system ( const char * command );

for executing an executable external program from CPP program.

I want to give absolute and relative Path to the folder where executable was present. I was using/calling the system function in the program name “testExt.cpp

#include <stdlib.h>

int main(){
system(“dir C:\\blabla”);
system(“C:\\blabla\\xyz.exe”);
return 0;
}

Then compile using g++
c:\> g++ -g testExt.cpp -o teste

then ran the executable file “teste.exe” which we compiled above.

c:\> teste.exe
dir: C:blabla: No such file or directory
C:blablaxyz.exe: not found

Error. WHY?

You will notice one very surprising thing in that the backslash is not present in any of the command output. So, it will not follow the exact PATH you mentioned in the program. Even you try to write your path like this to fix the problem.
system("\"C:\\blabla\\xyz.exe\"");

It will still not help as it will still give different error message ‘not found’ instead of correct path and correct name of executable. Following the error message from the above another way of writing Path to the executable

C:\blabla\xyz.exe: not found

SOLUTION:

The main reason behind is that g++ compiler understand path in terms of UNIX/LINUX based system. So, lets re write “testExt.cpp” Program.

#include <stdlib.h>

int main(){
system(“dir /blabla”);
system(“/blabla/xyz.exe”);
return 0;

Recompile the program using g++ like we did above and run the executable.

BAAAAM!!! It worked!!! you can see the content of the folder ‘blabla’ and your executable ‘xyz.exe’ is called from your recompiled program.

Explanation:

The new re-written program starts with ‘/’ which is called root in UNIX/Linux based system.

In Windows system, ‘C:\’ have to replaced by ‘/’ and write your path using FORWARD SLASH as shown in the re-written program “testExt.cpp“.

Hope this may be helpful for you. Have a nice day!!! :)

  1 comment for “system() not recognizing path (with \\) using g++ complier for windows

Comments are closed.

Animated Social Media Icons Powered by Acurax Wordpress Development Company