我目前正在编写一个程序,该程序列出当前目录中的所有文件和子目录。
我正在努力更改目录,因此在列出所有目录和子目录后,我需要能够更改目录。在我的代码中,我有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/