Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether path is absolute or relative

Using C++, I need to detect whether given path (file name) is absolute or relative. I can use Windows API, but don't want to use third-party libraries like Boost, since I need this solution in small Windows application without expernal dependencies.

like image 643
Alex F Avatar asked Mar 21 '11 12:03

Alex F


People also ask

How do you know if a path is absolute or relative in Python?

isabs() method in Python is used to check whether the specified path is an absolute path or not.

How do you distinguish the following two paths relative and absolute?

The main difference between an absolute and a relative path is that an absolute path specifies the location from the root directory whereas a relative path is related to the current directory.

Should I use relative path or absolute path?

Relative links show the path to the file or refer to the file itself. A relative URL is useful within a site to transfer a user from point to point within the same domain. Absolute links are good when you want to send the user to a page that is outside of your server.


2 Answers

The Windows API has PathIsRelative. It is defined as:

BOOL PathIsRelative(
  _In_  LPCTSTR lpszPath
);
like image 66
Daniel A. White Avatar answered Sep 19 '22 06:09

Daniel A. White


Beginning with C++14/C++17 you can use is_absolute() and is_relative() from the filesystem library

#include <filesystem> // C++17 (or Microsoft-specific implementation in C++14)

std::string winPathString = "C:/tmp";
std::filesystem::path path(winPathString); // Construct the path from a string.
if (path.is_absolute()) {
    // Arriving here if winPathString = "C:/tmp".
}
if (path.is_relative()) {
    // Arriving here if winPathString = "".
    // Arriving here if winPathString = "tmp".
    // Arriving here in windows if winPathString = "/tmp". (see quote below)
}

The path "/" is absolute on a POSIX OS, but is relative on Windows.

In C++14 use std::experimental::filesystem

#include <experimental/filesystem> // C++14

std::experimental::filesystem::path path(winPathString); // Construct the path from a string.
like image 22
Roi Danton Avatar answered Sep 23 '22 06:09

Roi Danton