#include <iostream>
#include <numeric>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
using file_buffer_ptr = std::unique_ptr<std::vector<char>>;
using file_buffer_iter = std::istreambuf_iterator<file_buffer_ptr::element_type::value_type>;
using file_list = std::vector<file_buffer_ptr>;
static file_buffer_ptr fillBuffer(const fs::path ¤tFile)
{
auto fileBuf = std::make_unique<file_buffer_ptr::element_type>();
fileBuf->reserve(fs::file_size(currentFile));
std::ifstream fileStream(currentFile, std::ios::binary);
fileBuf->assign(file_buffer_iter(fileStream), file_buffer_iter());
return fileBuf;
}
int main()
{
file_list files;
auto directory = "/tmp";
try {
for (auto& currentFile: fs::recursive_directory_iterator(
directory,
fs::directory_options::skip_permission_denied
))
{
if (!fs::is_regular_file(currentFile))
continue;
files.emplace_back(fillBuffer(currentFile));
}
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
}
std::clog << "Found " << files.size() << " files, total size " <<
std::accumulate(files.begin(), files.end(), 0,
[] (file_buffer_ptr::element_type::size_type total, const file_buffer_ptr &b) {
return total + b->size();
})
<< " bytes" << std::endl;
return 0;
}