flatten 20260225
This commit is contained in:
62
tjp/core/file/read.cpp
Normal file
62
tjp/core/file/read.cpp
Normal file
@@ -0,0 +1,62 @@
|
||||
// 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
|
||||
Reference in New Issue
Block a user