I've had trouble with this issue across many languages, most recently with C++.
The Issue Exemplified
Let's say we're working with C++ and have the following file structure for a project:
("Project" main folder with three [modules, data, etc] subfolders)
Now say:
- Our
maincode.cpp
is in the Project folder moduleA.cpp
is in modules folderdata.txt
is in data foldermoduleA.cpp
wants to readdata.txt
So the way I'd currently do it would be to assume maincode.cpp
gets compiled & executed inside the Project folder, and so hardcode the path data/data.txt
in moduleA.cpp
to do the reading (say I used fstream fs("data/data.txt")
to do so).
But what if the code was, for some reason, executed inside etc
folder?
Is there a way around this?
The Questions
- Is this a valid question? Or am I missing something with the wd (working directory) concept fundamentals?
- Are there any methods for working around absolute paths so as to solve this issue in C++?
- Are there any universal methods for doing the same with any language?
- If there are no reasonable methods, how would you approach this issue?
Please leave a comment if I missed any important details with the problem's illustration!
At some point the program has to make an assumption where the file(s) are. Either by getting it from user input or a relative path with the presumed filename. As already said in the comments, C++ recently got
std::filesystem
added in C++17 which can help you making cross-platform code that interacts with the hosts' filesystem.That being said, every program, big or small, has to make certain assumptions at some point, deleting or moving certain files is problematic for any program in case the program requires them to be at a certain location under a certain name. This is not solvable other than presenting the user with an error message etc.