Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
61 lines (48 sloc) 1.56 KB
//
// Program
// C++17 Filesystem: Directory iterator.
//
// Compiler
// Make sure that gcc support c++17 with file system module.
// - Use gcc-8 (g++ (Ubuntu 8.2.0-1ubuntu2~18.04) 8.2.0): sudo apt install gcc-8
//
// Compile
// g++ -Wall -Wextra -pedantic -std=c++17 -o 03-fs_test 03-fs_test.cxx -lstdc++fs
//
// Execution
// ./03-fs_test
//
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
// Iterate directory
void list_dir(fs::path dir_path, fs::directory_options opts, int level) {
std::string prepend = std::string(level * 2, ' ');
for(auto& p: fs::directory_iterator(dir_path, opts)) {
auto path = p.path();
if (fs::is_directory(path)) {
std::cout << prepend << "+ " << path.filename().string() << std::endl;
list_dir(path, opts, ++level);
level--;
}
else if (fs::is_regular_file(path)) {
std::cout << prepend <<"- " << path.filename().string() << std::endl;
}
}
}
//
// Entry function
//
int main(int argc, char *argv[]) {
fs::path tmp_path = fs::temp_directory_path();
std::cout << "Hello world -- std::filesystem" << std::endl;
std::cout << " - Temporary directory: " << tmp_path.string() << std::endl;
fs::directory_options opts = /* fs::directory_options::follow_directory_symlink | */
fs::directory_options::skip_permission_denied;
// Iterate directory recursively
list_dir(tmp_path, opts, 1);
// Suppress compiler warning(s)
(void)argc;
(void)argv;
return 0;
}
You can’t perform that action at this time.