C Path – How to Find Relative Path from Two Absolute Paths

absolute-pathc++pathrelative-path

Given two absolute paths, e.g.

  • /a/path/to/a
  • /a/path/to/somewhere/else

How can I get a relative path from one to the other, ../a?

In a sense, the opposite of what realpath does.

Best Answer

I answered a similar question here: Resolving a relative path without referencing the current directory on Windows.

There is no standard function for this. There is a function in vi-like-emacs for this purpose. A quick check of apropos relative shows me few other programs which likely implement this: revpath for example).

It could be done as a string-manipulation (no need to compute working directories):

  • start by finding the longest common prefix which ends with a path-separator.
  • if there is no common prefix, you are done
  • strip the common prefix from (a copy of...) the current and target strings
  • replace each directory-name in the current string with ".."
  • add that (with a path-separator) in front of the target string
  • return that combined string

The "done" in the second step presumes that you want to use a relative path to shorten the result. On the other hand, you might want to use a relative pathname regardless of the length. In that case, just skip the step (the result will be longer, but relative).

Related Question