To list all files in a directory using std::filesystem
, you can use the std::filesystem::directory_iterator
. This iterator allows you to iterate over the contents of a directory, providing access to each directory_entry
.
Here's a simple example demonstrating how to list all files and directories in a specified path:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path dir_path{R"(c:\test)"};
try {
for (const auto &entry
: fs::directory_iterator(dir_path)) {
std::cout << entry.path().string() << '\n';
}
} catch (fs::filesystem_error &e) {
std::cerr << e.what() << '\\n';
}
}
c:\test\file1.txt
c:\test\file2.txt
c:\test\subdir
In this example:
dir_path
as the path to the directory we want to list.for
loop to iterate over each entry in the directory using fs::directory_iterator
.entry.path()
method retrieves the path of each file and directory, and we can create a std::string()
from this object using the string()
method.You should include error handling because std::filesystem
operations can throw exceptions, particularly if the directory does not exist or there are permission issues. The try
block and catch
block handle any fs::filesystem_error
exceptions and print the error message.
This approach lists both files and directories. If you want to filter out directories and list only files, you can use the is_regular_file()
 method:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path dir_path{R"(c:\test)"};
try {
for (const auto &entry
: fs::directory_iterator(dir_path)) {
if (fs::is_regular_file(entry.status())) {
std::cout << entry.path().string() << '\n';
}
}
} catch (fs::filesystem_error &e) {
std::cerr << e.what() << '\n';
}
}
c:\test\file1.txt
c:\test\file2.txt
In this updated example, the if
statement checks if the current entry is a regular file before printing its path.
Answers to questions are automatically generated and may not have been reviewed.
Create, delete, move, and navigate through directories and files using the standard library's filesystem
module.