W
W
woolfcod2017-03-19 20:34:42
Programming
woolfcod, 2017-03-19 20:34:42

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

3 answer(s)
D
Dmitry, 2017-03-20
@TrueBers

The code
#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 &currentFile)
{
    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;
}

And handle has nothing to do with C ++, it is a feature of a specific operating system.

L
longclaps, 2018-01-14
@IAmJustSpace

Isn't it ? (min(n, m) - 1) * 2

T
tzlom, 2018-01-14
@tzlom

It seems to me that the problem has an analytical solution, i.e. it is possible to derive a function from the arguments M and N that would not require cycles when calculating the result.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question