从文件名获取在Windows中的驱动器盘符

8
有没有一种Windows API函数可以从Windows路径中提取驱动器号,例如:
U:\path\to\file.txt
\\?\U:\path\to\file.txt

在正确排序时

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

etc?

4个回答

13

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


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);  
}

谢谢 - 两个评论:你不需要复制数组指针,只需将数组本身作为参数传递给 PathBuildRoot。而且,如果你想初始化一个静态数组,只需使用 = {},因为这是通用解决方案,适用于所有类型和大小。 - Felix Dombek
@FelixDombek:修复好了,谢谢!这样更简洁,我喜欢。我对C++还是比较新手,非常感谢你的反馈。 - Tom
很酷。那么你可能会想知道,对于静态数组,您几乎总是可以使用 buff 来表示与 &buff[0] 相同的内容。它适用于函数调用、返回等(请参见 http://www.lysator.liu.se/c/c-faq/c-2.html,在表达式中,数组会衰减为指针,**除非**数组是 sizeof& 运算符的操作数,这在这里并不是这种情况)。 - Felix Dombek

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

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;
}

Windows API 函数在哪里? :P - R. Martinho Fernandes
1
@m0skit0:如果是带有备用NTFS流的相对路径,你的函数就无法工作了 ;) - Felix Dombek
我使用了你提供的示例,因为我在处理 Windows 系统方面经验不是很丰富 :) - m0skit0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接