'Check whether a path is absolute or relative

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



Solution 1:[1]

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.

Solution 2:[2]

Absolute paths tend to start with the / character. Anything else is pretty much relative from the working directory.

Even directories with .. sequences in them are considered absolute if they start with / since they end up at the same position in the file system (unless you change links and things but that's beyond the discussion of absolute and relative).

Solution 3:[3]

It's absolute if it begins with a /, otherwise relative.

Solution 4:[4]

Check if the path starts with / or not. if path starts with / you can assume it is absolute.

Solution 5:[5]

Check if the path starts with / or not. if path starts with / you can assume it is absolute otherwise it's relative means it will update from pwd(present working directory) But in Absolute case path will update relative to root directory

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brecht Sanders
Solution 2 paxdiablo
Solution 3 David Heffernan
Solution 4 masoud
Solution 5 Anshul garg