sapphire/src/FileIO.cpp
2022-06-16 15:56:10 +02:00

45 lines
1.2 KiB
C++

#include "FileIO.h"
#include "Error.h"
#include "sapphirepch.h"
#include <cstring>
#include <errno.h>
#include <filesystem>
#include <fstream>
std::string FileIO::read_all(const std::string& filename)
{
if (std::filesystem::is_directory(std::filesystem::status(filename)))
Error::throw_error_without_location("unable to open file " + filename + ": Is a directory");
std::ifstream file;
file.exceptions(std::ios::badbit | std::ios::failbit);
try
{
file.open(filename);
}
catch (const std::exception& e)
{
Error::throw_error_without_location("unable to open file " + filename + ": " + strerror(errno));
}
file.exceptions(std::ios::goodbit);
std::vector<char> file_chars;
char fchar;
while (file.good())
{
fchar = file.get();
if (fchar != -1) file_chars.push_back(fchar);
}
file.close();
return std::string(file_chars.begin(), file_chars.end());
}
void FileIO::write_all(const std::string& filename, const std::string& contents)
{
std::ofstream file(filename);
file << contents;
file.close();
}
std::string FileIO::remove_file_extension(const std::string& filename)
{
return filename.substr(0, filename.find_last_of('.'));
}