Files
core_misc/tjp/core/file/read.cpp
Timothy Prepscius fa54be052a flatten 20260225
2026-02-25 12:39:24 -05:00

63 lines
1.0 KiB
C++

// TJP COPYRIGHT HEADER
#ifdef TJP_CORE_HEADER_ONLY
#pragma once
#endif
#include <tjp/core/header_only/compile.h>
#include "read.hpp"
#include <tjp/core/exception/Exception.hpp>
#include <cstdio>
#include <fstream>
namespace tjp::core::file {
TJP_CORE_HEADER_ONLY_INLINE
Optional<Contents> read(const String& path)
{
std::ifstream file(path, std::ios::ate | std::ios::binary);
bool exists = (bool)file;
if (!exists || !file.is_open())
return {};
size_t fileSize = (size_t)file.tellg();
Contents buffer(fileSize);
file.seekg(0);
file.read(buffer.data(), buffer.size());
file.close();
return buffer;
};
TJP_CORE_HEADER_ONLY_INLINE
Contents require_read(const String& path)
{
if (auto result = read(path))
return *result;
throw Exception { "failed to read file " + String(path) };
}
TJP_CORE_HEADER_ONLY_INLINE
Optional<Contents> read(const StringView& path)
{
return read(String(path));
}
TJP_CORE_HEADER_ONLY_INLINE
Contents require_read(const StringView& path)
{
return require_read(String(path));
}
} // namespace