Skip to content

Instantly share code, notes, and snippets.

@amir-saniyan
Created July 22, 2020 16:53
Show Gist options
  • Save amir-saniyan/82199e0d865b470f5eb7e9feeb7e814e to your computer and use it in GitHub Desktop.
Save amir-saniyan/82199e0d865b470f5eb7e9feeb7e814e to your computer and use it in GitHub Desktop.
C++ helper functions to read and write files.

C++ File I/O

This gist contains C++ helper functions to read and write files.

FileHelper.h:

#include <string>
#include <vector>

std::vector<unsigned char> ReadAllBytes(const std::string& fileName);
void WriteAllBytes(const std::string& fileName, const std::vector<unsigned char>& data);

FileHelper.cpp:

#include <algorithm>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <vector>

std::vector<unsigned char> ReadAllBytes(const std::string& fileName)
{
    if(fileName.empty())
    {
        throw std::invalid_argument("Invalid file name.");
    }

    std::ifstream fileStream(fileName, std::ios::in | std::ios::binary);

    if(!fileStream)
    {
        throw std::runtime_error("Could not open file: " + fileName);
    }

    fileStream.unsetf(std::ios::skipws);

    fileStream.seekg(0, std::ios::end);
    auto fileLength = fileStream.tellg();

    std::vector<unsigned char> result;
    result.reserve(static_cast<std::vector<unsigned char>::size_type>(fileLength));

    fileStream.seekg(0, std::ios::beg);
    result.insert
    (
        result.begin(),
        std::istream_iterator<unsigned char>(fileStream),
        std::istream_iterator<unsigned char>()
    );

    fileStream.close();

    return result;
}

void WriteAllBytes(const std::string& fileName, const std::vector<unsigned char>& data)
{
    if(fileName.empty())
    {
        throw std::invalid_argument("Invalid file name.");
    }

    std::ofstream fileStream(fileName, std::ios::out | std::ios::binary | std::ios::trunc);

    if(!fileStream)
    {
        throw std::runtime_error("Could not open file: " + fileName);
    }

    std::copy(data.cbegin(), data.cend(), std::ostream_iterator<unsigned char>(fileStream));

    fileStream.close();

    return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment