It’s quite easy to read the contents of a file to a vector at one go. For this we need to get the size of a file and ask vector to allocate a buffer to hold these many bytes (use vector::resize()). Here is a function which does this. Note that it’s a byte/char vector.
[sourcecode language=’cpp’]#include “vector”
void ReadFileToVector( const char* FileName, std::vector
using namespace std;
ifile.open( FileName, ios::in );
// Get file size
streamoff FileSize = ifile.tellg();
// Resize vector to file size
FileBuff.resize( FileSize, 0 );
// Read in file contents to buffer
Benefit of using a vector instead of a char pointer is that we don’t have to do memory management and also we are directly accessing this buffer so no reallocations occur internally but we’ll have to check for allocation failure after calling vector::resize since files can be of huge sizes. You can optimize this further, post a comment if you find any issue/optimization. Also note that there are other ways to achieve the same behavior for e.g. using istream_iterator and back_inserter but this does cause frequent reallocations in a vector IMO making things slower.