使用C++,我需要检测给定路径(文件名)是绝对路径还是相对路径。我可以使用Windows API,但不想使用像Boost这样的第三方库,因为我需要在没有外部依赖的小型Windows应用程序中使用此解决方案。
Windows API 中有PathIsRelative
函数。它的定义如下:
BOOL PathIsRelative(
_In_ LPCTSTR lpszPath
);
从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.
yes
、no
和error determining
。2. 这个限制:maximum length MAX_PATH
。不幸的是,我没有找到一个可靠地完成这个任务的Windows API... - ahmd0