Answer the question
In order to leave comments, you need to log in
Get file handle and size C++?
Hello.
I am writing a program in C++, the program recursively searches for files on disks.
How can I implement the following:
Get file handle, file size and allocate memory for found files.
All this must be done in a do - while loop.
Please help me figure it out.
Answer the question
In order to leave comments, you need to log in
#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;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question