C++: Read file content into string

Sometimes you have to do something silly such as reading the entire contents of a file into a string. In this particular example we wish to end up with an std::string which contains the binary representation of a file - just as it resides on the disk.

There are several approaches to this. One of the more popular solutions to the problem is using boost’s boost::filesystem::load_string_file(). However, this comes with the common cost when working with boost: You have to use boost.

The following code snippet illustrates a function which achieves the same result but using only pure C++17:

#include <filesystem>
#include <fstream>

/**
 * Returns an std::string which represents the raw bytes of the file.
 *
 * @param path The path to the file.
 * @return The content of the file as it resides on the disk - byte by byte.
 */
[[nodiscard]]
static
std::string
file_contents(const std::filesystem::path& path)
{
    // Sanity check
    if (!std::filesystem::is_regular_file(path))
        return { };

    // Open the file
    // Note that we have to use binary mode as we want to return a string
    // representing matching the bytes of the file on the file system.
    std::ifstream file(path, std::ios::in | std::ios::binary);
    if (!file.is_open())
        return { };

    // Read contents
    std::string content{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};

    // Close the file
    file.close();

    return content;
}

Feel free to use this however you see fit. However, as usual this comes without any form of warranty - use at your own risk!

comments powered by Disqus