How do you read n bytes from a file and put them into a vector<uint8_t> using iterators?

喜你入骨 提交于 2021-02-19 15:25:07

问题


Based on this this question:

How to read a binary file into a vector of unsigned chars

In the answer they have:

std::vector<BYTE> readFile(const char* filename)
{
    // open the file:
    std::basic_ifstream<BYTE> file(filename, std::ios::binary);

    // read the data:
    return std::vector<BYTE>((std::istreambuf_iterator<BYTE>(file)),
                              std::istreambuf_iterator<BYTE>());
}

Which reads the entire file into the vector.

What I want to do is read (for example) 100 bytes at a time in the vector, then do stuff, and then read the next 100 bytes into the vector (clear the vector between). I don't see how to specify how much of the file to read (i.e. how to setup the iterators). Is that even possible?

I am trying to avoid having to write my own code loop to copy each byte at a time.


回答1:


You can use ifstream::read for that.

std::vector<BYTE> v(100);
while ( file.read(reinterpret_cast<char*>(v.data()), 100) )
{
   // Find out how many characters were actually read.
   auto count = file.gcount();

   // Use v up to count BTYEs.
}



回答2:


You could write a function to:

void readFile( const std::string &fileName, size_t chunk, std::function<void(const std::vector<BYTE>&)> proc )
{
    std::ifstream f( fileName );
    std::vector<BYTE> v(chunk);
    while( f.read( v.data(), v.size() ) ) {
        v.resize( f.gcount() );
        proc( v );
        v.resize( chunk );
    }
}

then usage is simple:

void process( const std::vector<BYTE> &v ) { ... }

readFile( "foobar", 100, process ); // call process for every 100 bytes of data

or you can use lambda etc for callback.




回答3:


Or you can write your own function for that:

template<typename Data>
std::istreambuf_iterator<Data> readChunk(std::istreambuf_iterator<Data>& curr, std::vector<Data>& vec, size_t chunk = 100) {
    for (int i = 0; curr != std::istreambuf_iterator<Data>() && i < chunk; ++i, ++curr) {
        vec.emplace_back(*curr);
    }
    return curr;
}

and use it as:

std::ifstream file("test.cpp");
std::vector<BYTE> v;
std::istreambuf_iterator<BYTE> curr(file);
readChunk<BYTE>(curr, v);

And you can call this function again.



来源:https://stackoverflow.com/questions/50491833/how-do-you-read-n-bytes-from-a-file-and-put-them-into-a-vectoruint8-t-using-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!