engine/src/util/files.cpp

78 lines
1.6 KiB
C++
Raw Normal View History

2022-11-22 21:50:06 +00:00
#include "util/files.hpp"
2022-12-15 15:54:11 +00:00
#include "stb_image.h"
2022-11-22 21:50:06 +00:00
#include <fstream>
namespace engine::util {
std::unique_ptr<std::vector<char>> readTextFile(const std::string& path)
{
auto buffer = std::make_unique<std::vector<char>>();
std::ifstream file(path, std::ios::ate);
if (file.is_open() == false) {
throw std::runtime_error("Unable to open file " + path);
}
// reserve enough space for the text file, but leave the size at 0
buffer->reserve(file.tellg());
file.seekg(0);
while (!file.eof()) {
char c{};
file.read(&c, 1);
buffer->push_back(c);
}
file.close();
return buffer;
}
2022-11-23 16:20:08 +00:00
std::unique_ptr<std::vector<uint8_t>> readBinaryFile(const std::string& path)
{
std::ifstream file(path, std::ios::ate | std::ios::binary);
if (file.is_open() == false) {
throw std::runtime_error("Unable to open file " + path);
}
auto buffer = std::make_unique<std::vector<uint8_t>>(file.tellg());
file.seekg(0);
file.read((char*)buffer->data(), buffer->size());
file.close();
return buffer;
}
2022-12-15 15:54:11 +00:00
// returns false if unable to open file
std::unique_ptr<std::vector<uint8_t>> readImageFile(const std::string& path, int *width, int *height)
{
int x, y, n;
unsigned char *data = stbi_load(path.c_str(), &x, &y, &n, STBI_rgb_alpha);
if (data == nullptr) {
throw std::runtime_error("Unable to open file " + path);
}
const size_t size = (size_t)x * (size_t)y * 4;
auto buffer = std::make_unique<std::vector<uint8_t>>(size);
memcpy(buffer->data(), data, buffer->size());
*width = x;
*height = y;
stbi_image_free(data);
return buffer;
}
2022-11-22 21:50:06 +00:00
}
2022-11-23 16:20:08 +00:00