~redstrate/libxiv

4279dc28279d930e1c9eebfb4541126eb563934e — Joshua Goins 2 years ago 98793ef
Add memory buffer read/write functions
2 files changed, 32 insertions(+), 3 deletions(-)

M include/memorybuffer.h
A src/memorybuffer.cpp
M include/memorybuffer.h => include/memorybuffer.h +3 -3
@@ 5,6 5,7 @@
#include <istream>
#include <memory>
#include <cstring>
#include <vector>

enum class Seek {
    Current,


@@ 41,8 42,6 @@ struct MemoryBuffer {
        position = end;
    }



    size_t size() const {
        return data.size();
    }


@@ 142,4 141,5 @@ private:
    size_t position = 0;
};

void write_buffer_to_file(const MemoryBuffer& buffer, std::string_view path);
\ No newline at end of file
void write_buffer_to_file(const MemoryBuffer& buffer, std::string_view path);
MemoryBuffer read_file_to_buffer(std::string_view path);
\ No newline at end of file

A src/memorybuffer.cpp => src/memorybuffer.cpp +29 -0
@@ 0,0 1,29 @@
#include "memorybuffer.h"

void write_buffer_to_file(const MemoryBuffer& buffer, std::string_view path) {
    FILE* file = fopen(path.data(), "wb");
    if(file == nullptr)
        throw std::runtime_error("Failed to open file for writing.");

    fwrite(buffer.data.data(), buffer.data.size(), 1, file);

    fclose(file);
}

MemoryBuffer read_file_to_buffer(std::string_view path) {
    FILE* file = fopen(path.data(), "rb");
    if(file == nullptr)
        throw std::runtime_error("Failed to open file for reading.");

    fseek(file, 0, SEEK_END);
    size_t size = ftell(file);
    fseek(file, 0, SEEK_SET);

    MemoryBuffer buffer;
    buffer.data.resize(size);
    fread(buffer.data.data(), size, 1, file);

    fclose(file);

    return buffer;
}
\ No newline at end of file