2011-08-19 109 views
4

是否有一个Windows API函数从作为获取驱动器盘符在Windows

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

一个Windows路径,提取的驱动器盘符,而正确地整理出来

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

等?

回答

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

Windows API函数在哪里? :P –

+1

@ m0skit0:如果你的函数是一个具有备用NTFS流的相对路径,则不起作用;) –

+0

我使用了你提供的例子,因为我不是很有经验的使用Windows :) – m0skit0

3

下面是与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); 
} 
+0

谢谢 - 两条评论:你不需要复制数组指针,只需使用数组本身作为'PathBuildRoot'的参数即可。而且,如果你想初始化一个静态数组,只需使用'= {}',因为这是一个通用的解决方案,适用于所有类型和大小。 –

+0

@FelixDombek:固定,谢谢!这更干净,我喜欢它。我对C++还是比较新的,你的反馈是赞赏 – Tom

+0

这很酷。那么你可能有兴趣知道你可以(几乎)总是使用'buff'来表示与静态数组的'&buff [0]'相同的东西。适用于函数调用,返回等(请参阅http://www.lysator.liu.se/c/c-faq/c-2.html,数组衰减为表达式**中的指针,除了**时数组是一个'sizeof'或'&'操作符的操作数在这里不是这种情况) –

1

根据您的要求,您可能还需要考虑GetVolumePathName得到挂载点,这可能是也可能不是驱动器号。