5#ifndef GEMMI_FILEUTIL_HPP_
6#define GEMMI_FILEUTIL_HPP_
13#include <initializer_list>
17#if defined(_WIN32) && !defined(GEMMI_USE_FOPEN)
25 std::initializer_list<const char*>
exts) {
26 size_t pos = path.find_last_of(
"\\/");
27 std::string
basename = pos == std::string::npos ? path : path.substr(pos + 1);
28 for (
const char* ext :
exts) {
29 size_t len = std::strlen(ext);
48typedef std::unique_ptr<std::FILE, needs_fclose>
fileptr_t;
52#if defined(_WIN32) && !defined(GEMMI_USE_FOPEN)
55 if ((file = ::_wfopen(
wpath.c_str(),
wmode.c_str())) ==
nullptr)
57 if ((file = std::fopen(path,
mode)) ==
nullptr)
59 sys_fail(std::string(
"Failed to open ") + path +
60 (*
mode ==
'w' ?
" for writing" :
""));
67 if (path[0] ==
'-' && path[1] ==
'\0')
72inline std::size_t
file_size(std::FILE* f,
const std::string& path) {
75 long length = std::ftell(f);
86 return *
reinterpret_cast<char *
>(&x) == 1;
90 char*
bytes =
static_cast<char*
>(start);
95 char*
bytes =
static_cast<char*
>(start);
101 char*
bytes =
static_cast<char*
>(start);
110 std::unique_ptr<
char,
decltype(&std::free)> ptr_;
115 explicit operator bool()
const {
return (
bool)ptr_; }
116 char*
data() {
return ptr_.get(); }
117 const char*
data()
const {
return ptr_.get(); }
118 size_t size()
const {
return size_; }
122 char*
new_ptr = (
char*) std::realloc(ptr_.get(), n);
124 fail(
"Out of memory.");
125 (
void) ptr_.release();
133 std::memmove(
data(),
data() + n, n);
144 if (std::fread(
buffer.data(), size, 1, f.get()) != 1)
165 if (
input.is_compressed())
166 return input.uncompress_into_buffer();
167 if (
input.is_stdin())
const char * data() const
fail(), unreachable() and __declspec/__attribute__ macros
void swap_eight_bytes(void *start)
void swap_four_bytes(void *start)
CharArray read_into_buffer(T &&input)
CharArray read_stdin_into_buffer()
std::size_t file_size(std::FILE *f, const std::string &path)
std::wstring UTF8_to_wchar(const char *in)
std::string path_basename(const std::string &path, std::initializer_list< const char * > exts)
fileptr_t file_open(const char *path, const char *mode)
void swap_two_bytes(void *start)
GEMMI_COLD void sys_fail(const std::string &msg)
CharArray read_file_into_buffer(const std::string &path)
reading file into a memory buffer (optimized: uses fseek to determine file size)
void fail(const std::string &msg)
fileptr_t file_open_or(const char *path, const char *mode, std::FILE *dash_stream)
std::unique_ptr< std::FILE, needs_fclose > fileptr_t
void operator()(std::FILE *f) const noexcept
Conversion between UTF-8 and wchar. Used only for file names on Windows.