Issue
I have a project structure like this -
|Project
|--data
| |--assets
| |--file1.txt
| |--file2.txt
|--Module
| |--src
| |--dumpFileToAssets.cpp
|--build
| |--out.exe
The binary is written into build/out.exe
. So from my understanding the relative path is wrt the binary being generated.
Code snippet from dumpFileToAssets.cpp
Full path works -
std::string path = "/Users/Username/Project/data/assets/file1.txt"
ofstream myfile;
myfile.open (path);
myfile << "Writing this to a file.\n";
myfile.close();
Relative path from the build directory does not work -
meaning file1.txt
is not generated in the .open()
call and hence not written -
std::string path = "./../data/assets/file1.txt"
ofstream myfile;
myfile.open (path);
myfile << "Writing this to a file.\n";
myfile.close();
Question - Is my understanding that any relative path inside the code is wrt to the binary path where the binary is generated
correct ?
Or can I access the Project
root path inside code to achieve this ??
PS : Here are my findings -
- When I run the binary from terminal, it works.
- When I run an Xcode version of the project, the
out.exe
path is different, so it does not work, and I have to change the path wrt to the newout.exe
path
Solution
Your understanding of the working directory is incorrect. There are multiple ways to run your application and each time the working directory is different
cd /Users/Username/Project/
./build/out.exe
The working directory is /Users/Username/Project/
cd build
./out.exe
The working directory is /Users/Username/Project/build
mkdir sub
cd sub
../out.exe
The working directory is /Users/Username/Project/build/sub
On Windows, the working directory may even be a different drive:
D:
cd \test
C:\Users\Username\Project\build\out.exe
The working directory is D:\test
If you want to open a file relative to the executable, then determine the path of the executable first, which is not trivial. Note that argv[0]
may be a symbolic link and not the executable itself (like less
is a link to more
).
Answered By - Thomas Weller Answer Checked By - Mary Flores (WPSolving Volunteer)