Question

I just tried to run a new process by resolving its location via PATH env. var. Since I use Qt this means I added

X:\folder\

to my PATH variable and in my starter application I am calling

QProcess::startDetached("test.exe")

which actually works.

However test.exe writes data to its working directory. This data ends up in the directory of the starter application instead of X:\folder\ which is not what I want.

I tested the behaviour directly in the windows command line by typing "test.exe" in the CLI and it is the same there (having the data written to the current directory).

Is there a way (in C++ or command line) to start a process using PATH while also using the directory found in PATH as working directory of the new process?

I could search PATH for my own, analyze the finding and start the program by another QProcess::startDetached() overload but I wonder if there is an easier way.

Was it helpful?

Solution 2

There are at least 3 options without complicated configurations.

1 - From your calling application change current directory to where your test.exe program is located. That way, files will go to the desired directory. BUT then it is possible that the calling application will have problems or generate output where it should not, so a new change of current directory in the calling application is needed

2 - Pass as parameter to your test.exe where it should generate its files.

3 - Determine from your test.exe where it is located and use this information to change current directory for this process, or, knowing the path, generate the files in the same directory it is located.

TCHAR szPath[MAX_PATH];

if( !GetModuleFileName( NULL, szPath, MAX_PATH ) ) {
    // handle error in GetModuleFileName
} else {
    // now, szPath contains file path
};

This is the standard windows way of retrieving the location of the current process. Reference here: GetModuleFileName

OTHER TIPS

The OS will not "move to the current directory" when you use a path. You will have to do that yourself. (In most cases, you wouldn't really WANT the application to move to a different directory - what if the compiler did that when you do gcc foo.c - then you'd have to pass the full path to everything, since you certainly don't want to put your source files in where the compiler lives - in many cases you probably couldn't even write to that directory on a Unix/Linux system).

You will have to either prepend the correct folder [and I would suggest that using the applications install directory may not be the best place!], or do chdir(...) to change the current working directory to where you want data to be. Most applications (that use the principle of storing files in a particular place like this) store a "default directory" in a setting somewhere, so the user can change the setting to suit his/her setup.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top