【问题标题】:Get drive letter from filename in Windows从 Windows 中的文件名获取驱动器号
【发布时间】: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


    【解决方案1】:

    PathGetDriveNumber 如果路径有驱动器号,则返回 0 到 25(对应于“A”到“Z”),否则返回 -1。

    【讨论】:

      【解决方案2】:

      这里的代码将接受的答案(谢谢!)与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);  
      }
      

      【讨论】:

      • 谢谢 - 两个 cmets:您不需要复制数组指针,只需使用数组本身作为参数到 PathBuildRoot。而且,如果你想初始化一个静态数组,只需使用= {},因为这是通用解决方案,适用于所有类型和大小。
      • @FelixDombek:已修复,谢谢!这个比较干净,我喜欢。我对 C++ 还是很陌生,感谢您的反馈
      • 这很酷。那么您可能有兴趣知道您可以(几乎)始终使用buff 来表示与静态数组的&amp;buff[0] 相同的含义。适用于函数调用、返回等(请参阅lysator.liu.se/c/c-faq/c-2.html,当数组是sizeof&amp; 运算符的操作数时,数组会衰减为表达式中的指针except,但情况并非如此这里)
      【解决方案3】:

      根据您的要求,您可能还需要考虑使用GetVolumePathName 来获取挂载点,该挂载点可能是也可能不是驱动器号。

      【讨论】:

        【解决方案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;
        }
        

        【讨论】:

        • Windows API 函数在哪里? :P
        • @m0skit0:如果它是具有备用 NTFS 流的相对路径,则您的函数不起作用;)
        • 我使用了您提供的示例,因为我使用 Windows 的经验不是很丰富 :)
        猜你喜欢
        • 1970-01-01
        • 2011-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多