How do I make sure fopen() opens a file relative to the executable rather than my current directory in C++?

2.8k Views Asked by At

I have a C++ program compiled with MinGW on Windows 7 that calls fopen(), specifying a file with a relative path. The program works fine if you run the executable in it's own directory, but I've noticed that fopen() will not find the specified file if I were to run the program with command line in a different directory. For example, if my executable "foo.exe" and specified file "bar.txt" are located in "C:\project\build\" and I run the exe while in "C:\project\", fopen() will not find the file. Is there some workaround for this using the code or compiler flags?

1

There are 1 best solutions below

0
On BEST ANSWER

I can see this being necessary to access resources which are in a specified location relative to the executable, though without the absolute path of the executable file itself being known. I would suggest getting the absolute path to the executable file, probably using one of the methods described in Get path of executable, and then either changing the process's working directory to the parent directory of the executable, or constructing an absolute path to the file you want to open by resolving the relative path you have against that directory. Then you can pass the result to fopen().