【问题标题】:from all listed files and subdirectories change a directory从所有列出的文件和子目录中更改目录
【发布时间】:2020-06-21 21:44:31
【问题描述】:

我目前正在编写一个程序,列出当前目录中的所有文件和子目录。

我正在为更改目录的能力而苦苦挣扎,因此在列出所有目录和子目录后,我需要能够更改目录。在我的代码中,我有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;
}

【问题讨论】:

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


    【解决方案1】:

    你可以用递归来实现它。使用循环创建 listDirectory(std::string &amp;&amp; path) 函数,您拥有该函数,但为文件和目录添加不同的行为。 这是一个伪代码:

    void listDirectory(const std::string &path) {
        for (自动文件: fs::directory_iterator(path)) {
            如果(fs::is_directory(文件)){
                列表目录(文件);
            }
            别的 {
                std::cout 
        

    【讨论】:

    • 此函数中不需要右值引用。此外,该代码无法编译,因为 file 变量是左值。
    猜你喜欢
    • 2012-11-14
    • 2012-09-02
    • 2011-03-01
    • 2017-05-01
    • 2016-01-16
    • 2014-10-16
    • 1970-01-01
    相关资源
    最近更新 更多