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

530 views Asked by At

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!

3

There are 3 answers

0
Hatted Rooster On BEST ANSWER

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.

0
Dan M. On

As @Hatted Rooster said, it's not generally solvable for some arbitrary file without making some assumptions, however there are frameworks that allow you to "store" some files in the resources embedded into the executable (or otherwise). Those frameworks would usually allow your to handle such files in a opaque way, without the need to rely on a current working dir or relative paths.

For example, see the Qt Resource System.

0
LuckyLuke1984 On

Your program can deduce the path from argv[0] in the main call, if you know that it is always relative to your executable or you use an absolute path like "C:\myProgram\data\data.txt". The second approach works in every language.