Wednesday, 28 August 2013

Efficient way of reading part of a file into an std::vector?

Efficient way of reading part of a file into an std::vector?

Refering to this question: Efficient way of reading a file into an
std::vector<char>? I need a function that does the followig thing:
void readFromFile( std::vector< unsigned char >& buffer,
string filename,
size_t offset, size_t count );
so the function read from the file from offset to offset + count into vector;
void readFromFile( std::vector< unsigned char >& buffer,
string filename,
size_t offset, size_t count )
{
// get file size and reallocate the buffer
size_t fsize = filesize( filename );
buffer.reserve( buffer.size() + size );
// open the file
ifstream file( filename );
// first way
file.seekg( offset );
file.read( ???? )
// second way
istreambuf_iterator< unsigned char > from( file );
istreambuf_iterator< unsigned char > eof;
advance( from, offset );
copy( from, eof, back_inserter( buffer );
}
In the first way I don't know how to read the file at once. In the second
way the read operation is quite slow because I read byte per byte.
Are better alternatives?

No comments:

Post a Comment