Search code examples
directoryrelative-pathabsolute-path

In terms of file directories, in what situation would it be better to use an absolute pathway over a relative pathway and vice versa


I understand the difference between the two, being that an absolute pathway points to a specific file from the root and a relative path points to a file from the current directory but i cant find a situation of where one would be better than the other and vice versa.


Solution

  • The main assumption is that you don't know for sure where your project will be installed

    Based on that assumption:

    • Use a relative path for things within your own project, so that you can find them no matter where your project is placed. Your own resources should always be in the same place relative to the executable/project root, no matter where the project root is placed.

    • Use an absolute path for system files or locations. They should never really move, but may be in a different relative location to your project. As such, base their location off the system root (ie an absolute path).

    The main exception to this is where you're able to determine your own base path, and then recreate the full path by adding the relative path to that base path... which is essentially the same thing as just using the relative path. Occasionally used in web projects when dealing with virtual directories and URL's, as it allows you to produce consistent URL's eg in a "copy the link to this page"