是否可以使用 std::filesystem 获取根名称列表?

Is possible to get list of root names with std::filesystem?

我知道如何获取 root name for some path and there is std::filesystem::directory_iterator 遍历目录。

但是如何获取包含根名称的列表?如果不可能,那为什么呢?

看看最近开源的 Microsoft std::filesystem 实现,更具体地说 helper function _Find_root_name_end:

        // This is the place in the generic grammar where library implementations have the most freedom.
        // Below are example Windows paths, and what we've decided to do with them:
        // * X:DriveRelative, X:\DosAbsolute
        //   We parse X: as root-name, if and only if \ is present we consider that root-directory
        // * \RootRelative
        //   We parse no root-name, and \ as root-directory
        // * \server\share
        //   We parse \server as root-name, \ as root-directory, and share as the first element in relative-path.
        //   Technically, Windows considers all of \server\share the logical "root", but for purposes
        //   of decomposition we want those split, so that path(R"(\server\share)").replace_filename("other_share")
        //   is \server\other_share
        // * \?\device
        // * \??\device
        // * \.\device
        //   CreateFile appears to treat these as the same thing; we will set the first three characters as root-name
        //   and the first \ as root-directory. Support for these prefixes varies by particular Windows version, but
        //   for the purposes of path decomposition we don't need to worry about that.
        // * \?\UNC\server\share
        //   MSDN explicitly documents the \?\UNC syntax as a special case. What actually happens is that the device
        //   Mup, or "Multiple UNC provider", owns the path \?\UNC in the NT namespace, and is responsible for the
        //   network file access. When the user says \server\share, CreateFile translates that into
        //   \?\UNC\server\share to get the remote server access behavior. Because NT treats this like any other
        //   device, we have chosen to treat this as the \?\ case above.

这突出了一些问题:

  • Windows 中的驱动器盘符可以来来去去,因此 "list of valid roots" 会因一次调用而异
  • \server\share 案例需要 "list of valid roots" 基本上枚举整个互联网,因为 \1.2.3.4 是一个有效的主机。