【问题标题】:How to get a specific sub-folder path under root path?如何获取根路径下的特定子文件夹路径?
【发布时间】:2017-07-24 14:25:13
【问题描述】:

我想获取根目录下特定文件夹的位置。 例如,我有一个根目录C:\Dummy,我在这个文件夹中有一个子目录:

C:\Dummy\10\20\MyFolder

现在我想获取C:\Dummy目录下子目录MyFolder的路径。

我将编写一个函数来传递两个输入: 1)“根文件夹”即C:\Dummy 2)“子目录名称”即MyFolder

String fun(string RootFolderPath, string subDirName)
{

  //if any of the sub directories consists of `subDirName` then return the 
  //path
  return subDirPath;
}

有什么方法可以实现吗?

请帮我解决这个问题。

【问题讨论】:

  • 您期望得到什么? 10\20\MyFolder?
  • @Kane,这就是我所期望的“C:\Dummy\10\20\MyFolder”。
  • 所以你想要类似std::string findDirectory(const std::string &root, const std::string &directory) 的东西,它会在文件系统上找到相应的目录并返回它的路径?您能否更新您的问题,详细说明您有哪些输入数据以及您期望什么输出?
  • @Kane,就像你提到的那样。我详细更新了我的问题。
  • 谢谢,现在问题出在哪里更清楚了。请在下面查看 acraig5075 的答案。如果你想使用WinAPI,也许你会在这里找到答案:stackoverflow.com/questions/25639874/…

标签: c++11 visual-c++


【解决方案1】:

使用实验性的filesystem 标准库可以如下完成:

#include <experimental\filesystem>

namespace fs = std::experimental::filesystem;

string search_path(const string &root, const string &search)
{
    fs::path root_path(root);
    fs::path search_path(search);

    for (auto &p : fs::recursive_directory_iterator(root_path))
        {
        if (fs::is_directory(p.status()))
            {
            if (p.path().filename() == search)
                return p.path().string();
            }
        }

    return "";
}

否则,您必须使用 windows.api 特定的 file management functions 像 FindFirstFile() 和 FindNextFile() 来进行遍历。或者也许是 Boost filesystem 库。

【讨论】:

    【解决方案2】:

    通过连接 RootFolderPathsubDirName 创建完整的目录路径(不要忘记在其间插入“\”)。并使用以下 2 个 Windows API:

    auto bDirExists = (::PathFileExists(path) && ::PathIsDirectory(path));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 1970-01-01
      • 2021-02-05
      • 2014-03-13
      • 2014-05-29
      • 1970-01-01
      • 2010-10-14
      相关资源
      最近更新 更多