Search code examples
c++file-ioworking-directoryfile-structure

Methods for opening a specific file inside the project WITHOUT knowing what the working directory will be


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:

  1. Our maincode.cpp is in the Project folder
  2. moduleA.cpp is in modules folder
  3. data.txt is in data folder
  4. moduleA.cpp wants to read data.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

  1. Is this a valid question? Or am I missing something with the wd (working directory) concept fundamentals?
  2. Are there any methods for working around absolute paths so as to solve this issue in C++?
  3. Are there any universal methods for doing the same with any language?
  4. 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!


Solution

  • 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.