Skip to content
Advertisement

Check whether a path is absolute or relative

How do you check whether a path is absolute or relative, using C on Linux?

Advertisement

Answer

On Unix like systems (incl. Linux, macOS)

If it starts with a slash it’s absolute, otherwise it’s relative. That is because everything is part of a single tree starting at the root (/) and file systems are mounted somewhere in this tree.

On Windows

Windows uses backslashes (though slashes are also supported these days) and drive letters. But it’s bit more complex:

  • A path starting with a drive letter followed by a colon not followed by a backslash (or slash) can be relative to that drive’s current directory.
  • A path starting with a backslash (or slash) is absolute but on the current drive, so in that sense it is in fact relative (to the top of the current drive).
  • A path starting with 2 backslashes is an UNC path (pointing to a network location) which is always absolute, except when the path starts with \? which is a special case to support longer paths.

So on Windows it’s best to use the PathIsRelative() (PathIsRelativeA/PathIsRelativeW) function to determine if the path is relative or not.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement