Add memory buffer read/write functions
This commit is contained in:
parent
98793efa70
commit
4279dc2827
2 changed files with 32 additions and 3 deletions
|
@ -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();
|
||||
}
|
||||
|
@ -143,3 +142,4 @@ private:
|
|||
};
|
||||
|
||||
void write_buffer_to_file(const MemoryBuffer& buffer, std::string_view path);
|
||||
MemoryBuffer read_file_to_buffer(std::string_view path);
|
29
src/memorybuffer.cpp
Normal file
29
src/memorybuffer.cpp
Normal file
|
@ -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;
|
||||
}
|
Reference in a new issue