Get drive letter from filename in Windows

拈花ヽ惹草 提交于 2019-12-23 09:28:10

问题


Is there a Windows API function to extract the drive letter from a Windows path such as

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

while correctly sorting out

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

etc?


回答1:


PathGetDriveNumber returns 0 through 25 (corresponding to 'A' through 'Z') if the path has a drive letter, or -1 otherwise.




回答2:


Here is code that combines the accepted answer (thanks!) with PathBuildRoot to round out the solution

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



回答3:


Depending on your requirements, you might also want to consider GetVolumePathName to get the mount point, which may or may not be a drive letter.




回答4:


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


来源:https://stackoverflow.com/questions/7122009/get-drive-letter-from-filename-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!