【问题标题】:filesystem parent path and a ".." string to get back to parent path文件系统父路径和“..”字符串返回父路径
【发布时间】:2020-11-27 17:16:21
【问题描述】:

我没有使用 boost,我使用的是 C++17 的文件系统,它基本上是基于 boosts 文件系统的。

我想使用 C++ 文件系统列出目录、文件名和父目录快捷方式“..”。 将目录和文件名添加到列表中没有问题,我这样做:

string path="C:\something\test";

//add missing code here:
//should find: ".." or not.

//add directories to list
for (auto& p : directory_iterator(path))
{
    if (p.is_directory())
    {
        string name = p.path().filename().string();
        list[index].push_back(name);
    }
}

//add files to list
for (auto& p : directory_iterator(path))
{
    if (!p.is_directory())
    {
        string filename = p.path().filename().string();   //hele filnavnet (med filtype)
        list[index].push_back(filename);
    }
}

这很好用,但如果我在像 C:\something\test\ 路径这样的子目录中,问题是我缺少“..”。我想知道是否有可用的父路径,使用文件系统最简单的方法是什么?

如果路径是“C:”也是一样,那么我的程序应该说“..”不可用。 如果我在 C:\something\test\

中,基本上列表可能看起来像这样
..
AnotherDirectory
YetAnotherDirectory
file1.txt
file2.txt
etc.txt

如果我在“C:” 列表看起来像这样(没有“..”)

Something
Directory2
file1.txt
command.com
autoexec.but
config.lol

【问题讨论】:

  • 你不能用std::filesystem::path::parent_path这个吗?
  • 这将如何工作?问题是 parent_path().string() 例如,当我在“C:\”中时,没有给我“..”。它给出了相同的名称。嗯。也许我可以检查 subdir 是否等于 parent_path() 这可能是我实际上没有想到的想法..
  • "...check wether the subdir is equal to parent_path()" -- 完全正确。不过只是猜测。没查过。

标签: c++ filesystems c++17 subdirectory directory-structure


【解决方案1】:

我从@G.M.那里得到了这个想法

if (fs::current_path() != fs::current_path().parent_path())
    MessageBox(NULL, ".. exists", "Message", MB_OK);
else
    MessageBox(NULL, ".. doesn't exist", "Message", MB_OK);

这是一种行之有效的 hacky 方法,但我不知道有什么更简单或更好的方法。

【讨论】:

    猜你喜欢
    • 2015-04-14
    • 2012-07-26
    • 2015-08-15
    • 1970-01-01
    • 2011-09-30
    • 2018-11-30
    • 1970-01-01
    • 2012-01-12
    • 2019-04-08
    相关资源
    最近更新 更多