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

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

24

Windows API 中有PathIsRelative函数。它的定义如下:

BOOL PathIsRelative(
  _In_  LPCTSTR lpszPath
);

2
@LightnessRacesinOrbit:虽然在99%的情况下它可以工作,但这并不是一个完美的解决方案。以下是两个主要原因:1. 从技术上讲,应该有三个返回选项:yesnoerror determining。2. 这个限制:maximum length MAX_PATH。不幸的是,我没有找到一个可靠地完成这个任务的Windows API... - ahmd0
1
请使用 #include <shlwapi.h>。 - Praveen Patel

16

从C++14/C++17开始,您可以使用filesystem库中的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)
}

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

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

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

std::experimental::filesystem::path path(winPathString); // Construct the path from a string.

1
非常好的回答,没有任何问题未解答,谢谢。 - Sabuncu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接