Get drive letter from file name in Windows

Is there a Windows API function to extract a drive letter from a Windows path, for example

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

when sorted correctly

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

etc.?

+4
source share
4 answers

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

+9
source

Here is the code that combines the accepted answer (thanks!) With PathBuildRoot to round off 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
source

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

+1
source
 #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; } 
0
source

All Articles