Search code examples
c++pathcode-organizationifstream

how to write path of external file in an included c++ source


Suppose I'm writing a library or a set of tools mytool where a class MyTool that other people can use is defined. Suppose I have a directory tree like this:

project
| - program1
    | - main1.cpp
...
| - mytool
    | - mytool.h
    | - mytool.cpp
    | - data.txt

in tool1.cpp I use the external binary huge file data.dat:

ifsteam f("data.txt");

the main1.cpp use mytool, but if mytool.(s)o is linked with main1.o the program can't find data.dat, for this case I need to change the previous line to:

ifstream f("../mytool/data.txt");

but I can't know where other people put mytool for example they can have a different directory tree:

project
| - program1
    | - main1.cpp
    | - mytool
        | - tool1.h
        | - tool2.cpp
        | - data.dat

In addition (am I right?) the path depend on where the program is executed.

The only solution I can imagine is to pass to the class contructor MyTool the path of data.dat but I want to keep hidden this file for the user.


Solution

  • You need to know the absolute path of the file, or else the path of the file relative to your working directory. One approach is to have a configuration script which the user runs before compiling your program. The script then hardcodes into your program the relevant path, so the program has the path hardwired in a manner customized for the user.

    Sometimes that's not an option because you don't want to distribute the source code, or because you wish to allow the path to change at runtime. Then you can read a configuration file at runtime which says where the file is. But this is just a layer of abstraction: you still need to know where that configuration file is. You might, for example, ask the system where the user's personal directory is, and then find the file there at that directory. This is a sort of mix between compile-time and runtime computation of the path.