Yes, std::filesystem::directory_iterator
can be used to get various attributes of files and directories, such as size, type, and timestamps. The std::filesystem::directory_entry
object provided by the iterator offers methods to retrieve these attributes.
Here’s how you can get the size and type (file or directory) of each entry:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::directory_iterator start{R"(c:\test)"};
fs::directory_iterator end{};
for (auto iter{start}; iter != end; ++iter) {
std::cout << iter->path().string();
if (iter->is_directory()) {
std::cout << " (Directory)";
} else if (iter->is_regular_file()) {
std::cout << " (" << iter->file_size()
<< " Bytes)";
}
std::cout << '\n';
}
}
c:\test\file1.txt (0 Bytes)
c:\test\file2.txt (1024 Bytes)
c:\test\directory (Directory)
You can also get timestamps like last modification time:
#include <chrono>
#include <ctime>
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
using namespace std::chrono;
fs::directory_iterator start{R"(c:\test)"};
fs::directory_iterator end{};
for (auto iter{start}; iter != end; ++iter) {
auto ftime = fs::last_write_time(iter->path());
auto sctp =
time_point_cast<system_clock::duration>(
ftime - fs::file_time_type::clock::now()
+ system_clock::now());
std::time_t cftime =
system_clock::to_time_t(sctp);
std::cout << iter->path().string()
<< " - Last Write Time: "
<< std::asctime(std::localtime(&cftime));
}
}
c:\test\file1.txt - Last Write Time: Mon Jun 10 17:21:40 2024
c:\test\file2.txt - Last Write Time: Mon Jun 10 17:21:40 2024
c:\test\file2.txt - Last Write Time: Mon Jun 10 17:26:19 2024
file_size()
to get the size of regular files.is_directory()
, is_regular_file()
, and other type-check methods.last_write_time()
to get the last modification time.For more advanced attributes, like permissions or ownership, you might need platform-specific APIs. However, basic attributes are well-covered by the standard library.
By leveraging these methods, you can gather comprehensive details about files and directories as you iterate through them using std::filesystem::directory_iterator
.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to iterating through the file system, using directory iterators and recursive directory iterators
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course