c++ - 从所有列出的文件和子目录更改目录

标签 c++ c++17 working-directory

我目前正在编写一个程序,该程序列出当前目录中的所有文件和子目录。
我正在努力更改目录,因此在列出所有目录和子目录后,我需要能够更改目录。在我的代码中,我有fs::is_directory(myPath),它告诉我该文件是否为目录,如果是,我想指向它的路径,然后从内部打印文件。我什至可以通过使用parent_path来做到这一点,但是我不知道该怎么做。

#include <iostream>
#include <filesystem>

using namespace std;

namespace fs = std::filesystem;

int main()
{
    fs::path myPath("C:\\Users\\xyz\\Desktop\\things");

    cout << "your path is : " << myPath << endl;
    cout << "name of this directory is : "<< myPath.filename() << endl;
    cout << fs::is_directory(myPath) << endl;                        
    cout << myPath.parent_path() << endl;                                             

    for(auto file : fs::directory_iterator(myPath)) {
        cout << file << " " << fs::is_directory(file) << endl;
    }
    return 0;
}

最佳答案

您可以通过递归实现它。创建一个带有循环的listDirectory(std::string && path)函数,但是要为文件和目录添加不同的行为。
这是一个伪代码:
无效listDirectory(const std::string&path){
对于(自动文件:fs::directory_iterator(path)){
如果(fs::is_directory(file)){
listDirectory(file);
}
其他{
std::cout <<文件;
}
}
}

关于c++ - 从所有列出的文件和子目录更改目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62504783/

相关文章:

c++ - 为右值特化 std::swap

c++ - 从速度和方向计算速度

c++ - 逗号运算符使 lambda 表达式成为非 constexpr

使用直接大括号初始化时c++编译错误 'expected ' ;' at end of declaration'

language-agnostic - 到底是谁拥有 'current working directory'?

c++ - 双向链表 remove()

c++ - 如何模拟模板化类中的函数?

c++ - 概念及申报顺序

unit-testing - Golang : tests and working directory

Mercurial:将补丁应用到工作目录