在Windows中从文件名中获取驱动器号

Fel*_*bek 6 c++ filesystems winapi drive-letter

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

U:\path\to\file.txt
\\?\U:\path\to\file.txt
Run Code Online (Sandbox Code Playgroud)

正确整理的同时

relative\path\to\file.txt:alternate-stream    
Run Code Online (Sandbox Code Playgroud)

等等?

cpr*_*mer 11

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


Tom*_*Tom 5

下面的代码结合了接受的答案(谢谢!)来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);  
}
Run Code Online (Sandbox Code Playgroud)