C++ Get all bytes of a file in to a char array?

Note: Start with Remy Lebeau’s answer. For general file reading, this answer covers the hard way to do the job; it better matched the specific needs of this specific asker, but won’t necessarily meet your needs as well as the std::vector and std::istreambuf_iterator approach Remy outlines.


Most of the time they are right about getline, but when you want to grab the file as a stream of bytes, you want ifstream::read().

//open file
std::ifstream infile("C:\\MyFile.csv");

//get length of file
infile.seekg(0, std::ios::end);
size_t length = infile.tellg();
infile.seekg(0, std::ios::beg);

// don't overflow the buffer!
if (length > sizeof (buffer))
{
    length = sizeof (buffer);
}

//read file
infile.read(buffer, length);

Docs for ifstream::seekg()

Docs for ifstream::tellg()

NOTE: seekg() and tellg() to get the size of the file falls into the category of “usually works”. This is not guaranteed. tellg() only promises a number that can be used to return to a particular point. That said…

Note: The file was not opened in binary mode. There can be some behind-the-scenes character translations, for example the Windows newline of \r\n being converted to the \n used by C++. length can be greater than the number of characters ultimately placed in buffer.

2019 rethink

size_t chars_read;
//read file
if (!(infile.read(buffer, sizeof(buffer)))) // read up to the size of the buffer
{
    if (!infile.eof()) // end of file is an expected condition here and not worth 
                       // clearing. What else are you going to read?
    {
        // something went wrong while reading. Find out what and handle.
    }
}
chars_read = infile.gcount(); // get amount of characters really read.

If you’re looping on buffered reads until you consume the whole file, you’ll want some extra smarts to catch that.

If you want to read the whole file in one shot, and can afford to use resizable buffers, take the advice in Remy Lebeau’s answer.

Leave a Comment