【发布时间】:2023-03-13 01:29:01
【问题描述】:
是否有 Windows API 函数可以从 Windows 路径中提取驱动器号,例如
U:\path\to\file.txt
\\?\U:\path\to\file.txt
在正确整理的同时
relative\path\to\file.txt:alternate-stream
等等?
【问题讨论】:
标签: c++ winapi filesystems drive-letter
是否有 Windows API 函数可以从 Windows 路径中提取驱动器号,例如
U:\path\to\file.txt
\\?\U:\path\to\file.txt
在正确整理的同时
relative\path\to\file.txt:alternate-stream
等等?
【问题讨论】:
标签: c++ winapi filesystems drive-letter
PathGetDriveNumber 如果路径有驱动器号,则返回 0 到 25(对应于“A”到“Z”),否则返回 -1。
【讨论】:
这里的代码将接受的答案(谢谢!)与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。而且,如果你想初始化一个静态数组,只需使用= {},因为这是通用解决方案,适用于所有类型和大小。
buff 来表示与静态数组的&buff[0] 相同的含义。适用于函数调用、返回等(请参阅lysator.liu.se/c/c-faq/c-2.html,当数组是sizeof 或& 运算符的操作数时,数组会衰减为表达式中的指针except,但情况并非如此这里)
根据您的要求,您可能还需要考虑使用GetVolumePathName 来获取挂载点,该挂载点可能是也可能不是驱动器号。
【讨论】:
#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;
}
【讨论】: