Question

I have a file saved to my desktop, when I open it with my program the working directory changes to the desktop, this means my program can not load in some files it needs as it searches for these in the working directory. Is there a way I can stop the working directory from changing like this?

Was it helpful?

Solution

You can just save your working directory at startup and use absolute paths. In fact, it's better to always open files with absolute paths, unless you really want to rely on the current working directory.

OTHER TIPS

There's a flag you can set to avoid the current directory from changing called OFN_NOCHANGEDIR

http://msdn.microsoft.com/en-us/library/ms646839(v=vs.85).aspx

You would be better off determining the processes location, then using it as the key for where to find the other files? There are many ways that programs can be launched, which effect the working directory.

See: The answer here for a good description of how to get the processes location and strip out the executable filename (look in the comments)

Essentially, you use: GetModuleFileName or GetModuleFileNameEx.

and then: PathRemoveFileSpec to remove the file name

Opening a file doesn't change your current directory. Perhaps you using the common open file dialog? Here is an article that will explain all about how that changes your current directory.

use SetCurrentDirectory to do that. You can locate the executable by using GetModuleFileName

TCHAR szFileName[MAX_PATH];

GetModuleFileName( NULL, szFileName, MAX_PATH )

... then compute the correct directory
SetCurrentDirectory(path);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top