List Files in Directory
How do I list all files in a directory using std::filesystem
?
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:
- We define
dir_path
as the path to the directory we want to list. - We use a
for
loop to iterate over each entry in the directory usingfs::directory_iterator
. - The
entry.path()
method retrieves the path of each file and directory, and we can create astd::string()
from this object using thestring()
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.
Working with the File System
Create, delete, move, and navigate through directories and files using the std::filesystem
library.