50 lines
1.2 KiB
C++
50 lines
1.2 KiB
C++
#pragma once
|
|
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
|
|
namespace LXC::Util
|
|
{
|
|
struct FileReadError
|
|
{
|
|
enum Reason
|
|
{
|
|
FileNotFound,
|
|
PermissionDenied,
|
|
NotAFile
|
|
};
|
|
|
|
FileReadError(const std::filesystem::path& _path, Reason _reason)
|
|
: path(_path), reason(_reason)
|
|
{}
|
|
|
|
std::filesystem::path path;
|
|
Reason reason;
|
|
};
|
|
|
|
inline ReturnVal<std::string, FileReadError> ReadFile(const std::filesystem::path& filepath)
|
|
{
|
|
// Checks the file exists //
|
|
if (!std::filesystem::exists(filepath))
|
|
return FunctionFail(FileReadError(std::filesystem::absolute(filepath), FileReadError::FileNotFound));
|
|
|
|
// Checks it is a regular file //
|
|
if (!std::filesystem::is_regular_file(filepath))
|
|
return FunctionFail(FileReadError(std::filesystem::absolute(filepath), FileReadError::NotAFile));
|
|
|
|
// Checks it can open the file //
|
|
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
|
|
if (!file)
|
|
return FunctionFail(FileReadError(std::filesystem::absolute(filepath), FileReadError::PermissionDenied));
|
|
|
|
// Copies the file to the output string //
|
|
const std::streamsize len = file.tellg();
|
|
file.seekg(0, std::ios::beg);
|
|
|
|
std::string contents(len, '\0');
|
|
file.read(&contents[0], len);
|
|
|
|
return contents;
|
|
}
|
|
}
|