I am trying to open a file within a large code.
I was told that, when dealing with files, it might be a better practice to use the absolute path rather than the relative path. However this code is to be used by different people, who might put the sources in different places (/home/username, or /home/username/desktop/, for example) so I think it might be better to use a relative path to access my configuration file, because I know where it is in relation to my cpp file.
Here is a short sum up of the location of the files relevant to my question:
-
the file I want to read is /home/me/myproject/config/myfile.txt
-
the file I am reading it from is /home/me/myproject/src/myfile.cpp
-
the file that contains ‘main’ is also /home/me/myproject/src/myfile.cpp (this one file is huge).
I’m launching the executable from eclipse. I think eclipse sets the working directory to the directory where ‘main’ is (/home/me/myproject/src/).
I am puzzled by the fact that when I’m about to call file.open(), the working directory (getcwd()) now is /home/me/myproject/. Apparently the working directory was modified by the code in between main() and my call to file.open().
My question is: it seems very error prone to rely on the working directory, if it can be changed by another part of the program. On the other hand, how else I am supposed to know where my configuration path is, given that I don’t know where the other developers usually put their sources ?
Are you sure about that? It appears to me that it is the top level of the project folder (ie, something like “/home/eclipse/myproject”, and not “/home/eclipse/src”. That would explain why:
Was it ever anything else? It is very unlikely that it was “changed by another part of the program” unless you explicitly did something to cause that.
It’s not clear to me that you understand the difference between source code and executable. Your source code file is not “run”. It is compiled into an executable, and that is what is run. With eclipse, these get put by default into Release/ or Debug/ (have a look), not a src/ directory. The (presumable) reason eclipse uses the toplevel directory is consistency between those versions, and so you can, eg, output relative to that.
That is definitely true regardless. There are OS specific ways to get the path to the user’s home directory. You should get that, and specify in the documentation where the config is to be kept. If the user cannot do that properly, it is not your fault — but issue an informative message, eg. “Config file not found!”.
Note that “other developers” do not necessarily include the source at all, since it is not required to run the executable.