检测路径是绝对路径还是相对路径

Ale*_*x F 14 c++ windows path visual-c++

使用C++,我需要检测给定的路径(文件名)是绝对的还是相对的.我可以使用Windows API,但不想使用像Boost这样的第三方库,因为我需要在没有经验依赖性的小型Windows应用程序中使用此解决方案.

Dan*_*ite 20

Windows API有PathIsRelative.它被定义为:

BOOL PathIsRelative(
  _In_  LPCTSTR lpszPath
);
Run Code Online (Sandbox Code Playgroud)

  • @LightnessRacesinOrbit:虽然它可以在99%的时间内工作,但它不是一个完美的解决方案.这有两个主要原因:1.技术上应该有三个返回选项:`yes`,`no`和`error determination`.2.此限制:`最大长度MAX_PATH`.不幸的是我找不到可以可靠地执行此操作的Windows API ... (2认同)

Roi*_*ton 9

从 C++14/C++17 开始,您可以使用is_absolute()is_relative()来自文件系统库

#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)
}
Run Code Online (Sandbox Code Playgroud)

路径“/”在 POSIX 操作系统上是绝对的,但在 Windows 上是相对的。

在 C++14 中使用 std::experimental::filesystem

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

std::experimental::filesystem::path path(winPathString); // Construct the path from a string.
Run Code Online (Sandbox Code Playgroud)