Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get drive letter from filename in Windows

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?

like image 265
Felix Dombek Avatar asked Aug 19 '11 13:08

Felix Dombek


3 Answers

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

like image 82
cprogrammer Avatar answered Oct 23 '22 01:10

cprogrammer


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);  
}
like image 29
Tom Avatar answered Oct 22 '22 23:10

Tom


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.

like image 3
Peter Tseng Avatar answered Oct 22 '22 23:10

Peter Tseng