7

是否有 Windows API 函数可以从 Windows 路径中提取驱动器号,例如

U:\path\to\file.txt
\\?\U:\path\to\file.txt

在正确整理的同时

relative\path\to\file.txt:alternate-stream    

ETC?

4

4 回答 4

12

如果路径具有驱动器号,则PathGetDriveNumber返回 0 到 25(对应于“A”到“Z”),否则返回 -1。

于 2011-08-19T13:09:29.063 回答
4

这是将接受的答案(谢谢!)与PathBuildRoot完善解决方案相结合的代码

#include <Shlwapi.h>    // PathGetDriveNumber, PathBuildRoot
#pragma comment(lib, "Shlwapi.lib")

/** Returns the root drive of the specified file path, or empty string on error */
std::wstring GetRootDriveOfFilePath(const std::wstring &filePath)
{
// get drive #      http://msdn.microsoft.com/en-us/library/windows/desktop/bb773612(v=vs.85).aspx
int drvNbr = PathGetDriveNumber(filePath.c_str());

if (drvNbr == -1)   // fn returns -1 on error
    return L"";

wchar_t buff[4] = {};   // temp buffer for root 

// Turn drive number into root      http://msdn.microsoft.com/en-us/library/bb773567(v=vs.85)
PathBuildRoot(buff,drvNbr);

return std::wstring(buff);  
}
于 2012-06-16T02:01:56.027 回答
3

根据您的要求,您可能还需要考虑GetVolumePathName来获取挂载点,它可能是也可能不是驱动器号。

于 2014-05-28T00:28:24.550 回答
0
#include <iostream>
#include <string>

using namespace std;

int main()
{    
    string aux;
    cin >> aux;
    int pos = aux.find(':', 0);
    cout << aux.substr(pos-1,1) << endl;
    return 0;
}
于 2011-08-19T13:12:34.817 回答