windows 检测路径是绝对路径还是相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5377642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect whether path is absolute or relative
提问by Alex F
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.
使用 C++,我需要检测给定的路径(文件名)是绝对的还是相对的。我可以使用 Windows API,但不想使用像 Boost 这样的第三方库,因为我需要在没有专家依赖的小型 Windows 应用程序中使用这个解决方案。
回答by Daniel A. White
The Windows API has PathIsRelative
. It is defined as:
Windows API 具有PathIsRelative
. 它被定义为:
BOOL PathIsRelative(
_In_ LPCTSTR lpszPath
);
回答by Roi Danton
Beginning with C++14/C++17 you can use is_absolute()
and is_relative()
from the filesystem library
从 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)
}
The path "/" is absolute on a POSIX OS, but is relative on Windows.
路径“/”在 POSIX 操作系统上是绝对的,但在 Windows 上是相对的。
In C++14 use std::experimental::filesystem
在 C++14 中使用 std::experimental::filesystem
#include <experimental/filesystem> // C++14
std::experimental::filesystem::path path(winPathString); // Construct the path from a string.
回答by Teolazza
I have boost 1.63 and VS2010 (c++ pre c++11), and the following code works.
我有 boost 1.63 和 VS2010(c++ pre c++11),以下代码有效。
std::filesystem::path path(winPathString); // Construct the path from a string.
if (path.is_absolute()) {
// Arriving here if winPathString = "C:/tmp".
}