2011-03-21 312 views
12

使用C++,我需要检测给定路径(文件名)是绝对路径还是相对路径。我可以使用Windows API,但不想使用Boost等第三方库,因为我需要小型Windows应用程序中的此解决方案,而无需依赖于附属程序。检测路径是绝对路径还是相对路径

+5

祝贺(http://msdn.microsoft.com/en-us/library/bb773660%28v=vs.85%29.aspx)。 – 2011-03-21 12:41:19

+2

@Tomalak Geret'kal - 你在“没有付出多少努力”中做了什么?无论如何,相同的链接已经发布为答案,我真的很感谢你的努力,谢谢,伙计。 – 2011-03-22 06:32:17

+0

@AlexFarber:他的观点是,如果你尝试过谷歌搜索,你将会把你放在正确的地方。 – 2014-03-03 16:22:58

回答

20

Windows API有PathIsRelative。它被定义为:

BOOL PathIsRelative(
    _In_ LPCTSTR lpszPath 
); 
+0

嗯。我笑了一下。 – 2011-03-21 12:40:56

+2

@LightnessRacesinOrbit:虽然它可以在99%的时间里工作,但它不是一个完美的解决方案。这里有两个主要原因:1.技术上应该有三个返回选项:'是','否'和'错误确定'。 2.此限制:“最大长度MAX_PATH”。不幸的是,我没有找到一个可以可靠地做到这一点的Windows API ... – ahmd0 2013-03-12 00:21:50

2

与开始C++ 14/C++ 17可以使用is_absolute()is_relative()filesystem library

#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. 
0

我有提高1.63和VS2010(C++预C++ 11),和下面的代码工作。在[不要把太多精力花在你的研究]

std::filesystem::path path(winPathString); // Construct the path from a string. 
if (path.is_absolute()) { 
    // Arriving here if winPathString = "C:/tmp". 
}