Most useful or reasonably complex applications need to save data such as user settings or saved games or browser history. I have been working on applications and games in C or C++ but I am not sure which of several ways to access files to use.
First the preferred location to store such data is queried. On Linux this would be the app name appended to /.
appended to getenv("HOME")
or getpwuid(getuid())->pw_dir
. A more advanced application would use a portable library or framework interface to query the location without manually checking the operating system and using the appropriate method. These concerns are mostly covered in Best way to save application settings.
The next part is accessing the files of various names within the directory. These are a few ways to do this:
- Simply concatenating
/Name
and storing this as a file path (either manually usingmemcpy()
in C or usingstd::filesystem::path
in C++). - Opening and maintaining a file descriptor to the application directory and then using relative filesystem calls such as
openat()
. - Using
chdir()
on the application directory at application launch followed byopen()
when the file is needed.
What are the implications of each of these ways including their advantages or drawbacks? More specifically:
- The first option uses string manipulation so is less clean in my opinion but does not necessarily rely on POSIX-specific functions and therefore is probably more portable, but is the OS having to traverse the directory trees from the beginning of an absolute path going to be slower than the other options?
- How will keeping extra file descriptors open as in the 2nd option affect memory usage or performance? How will this affect stability, as having too many open file descriptors can prevent opening new ones, is this likely going to be an issue?
- How would each of these options work out if I have subdirectories inside the app data directory such as
MyGame/Saves/<Save Name>
? The 3rd option will not work here well as I cannotchdir()
to a new directory temporarily without losing previous directory passed tochdir()
but is there a way around this?