【发布时间】:2011-07-19 15:46:22
【问题描述】:
使用 C++,我需要检测给定路径(文件名)是绝对路径还是相对路径。我可以使用 Windows API,但不想使用像 Boost 这样的第三方库,因为我需要在没有外部依赖的小型 Windows 应用程序中使用此解决方案。
【问题讨论】:
-
@AlexFarber:他的观点是,如果你尝试过,谷歌搜索就会把你带到正确的地方。
标签: c++ windows visual-c++ path
使用 C++,我需要检测给定路径(文件名)是绝对路径还是相对路径。我可以使用 Windows API,但不想使用像 Boost 这样的第三方库,因为我需要在没有外部依赖的小型 Windows 应用程序中使用此解决方案。
【问题讨论】:
标签: c++ windows visual-c++ path
Windows API 有PathIsRelative。定义为:
BOOL PathIsRelative(
_In_ LPCTSTR lpszPath
);
【讨论】:
yes、no 和error determining。 2.此限制:maximum length MAX_PATH。不幸的是,我没有找到可以可靠地执行此操作的 Windows API...
从 C++14/C++17 开始,您可以使用 filesystem library 中的 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 操作系统上是绝对路径,但在 POSIX 操作系统上是相对路径 窗户。
在 C++14 中使用 std::experimental::filesystem
#include <experimental/filesystem> // C++14
std::experimental::filesystem::path path(winPathString); // Construct the path from a string.
【讨论】: