Detect whether path is absolute or relative

2020-07-02 16:16发布

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.

3条回答
贪生不怕死
2楼-- · 2020-07-02 16:53

The Windows API has PathIsRelative. It is defined as:

BOOL PathIsRelative(
  _In_  LPCTSTR lpszPath
);
查看更多
我只想做你的唯一
3楼-- · 2020-07-02 16:54

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.
查看更多
\"骚年 ilove
4楼-- · 2020-07-02 17:06

I have boost 1.63 and VS2010 (c++ pre c++11), and the following code works.

std::filesystem::path path(winPathString); // Construct the path from a string.
if (path.is_absolute()) {
    // Arriving here if winPathString = "C:/tmp".
}
查看更多
登录 后发表回答