Search code examples
cdirectoryfilesystemsposix

How well defined and reliable is the behavior of passing a relative path to fopen()/open()/etc?


On all systems I know about, passing a name with no preceding path opens the path relative to the current working directory. However, how reliable is this practice, compared to, for example, always using an absolute path and prepending the result of getenv("HOME") or getpwuid(getuid()) (see Get home directory in Linux).

Which practice is more standard or reliable or recommended? It is certainly simpler to use the relative path with no preceding /, as there is no allocating memory to concatenate strings, but what are the downsides to this practice over manually concatenating the absolute path of the home directory?


Solution

  • Given that relative paths use the current working directory of program, the behavior depends on how well defined or reliable the 'default' working directory is, which in not necessarily the same as the home directory.

    Obtaining the home directory manually (via getenv("HOME") or getpwuid(getuid())), and then passing it to the chdir() function to manually define the working directory to be the home directory causes reliable behavior if I use relative paths for fopen()/open()/etc.