2011-03-21 355 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". 
}