From 60d540831b626443caddad12e04792bce91d3b4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=2E=20Yusuf=20Sar=C4=B1g=C3=B6z?= Date: Sat, 12 Aug 2023 21:42:31 +0300 Subject: [PATCH] gguf : roper closing of file --- gguf-util.h | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/gguf-util.h b/gguf-util.h index 6395cf304..70673404e 100644 --- a/gguf-util.h +++ b/gguf-util.h @@ -105,7 +105,6 @@ struct gguf_file { GGML_ASSERT(ret == 0); // same } - size_t write_str(const std::string & val) { size_t total_written = 0; const int32_t n = val.size(); @@ -127,14 +126,6 @@ struct gguf_file { return sizeof(val); } - void write_raw(const void * data, size_t size) { - fwrite(data, size, 1, fp); - } - - void read_raw(void * data, size_t size) { - fread(data, size, 1, fp); - } - template void write_val(const std::string & key, enum gguf_type type, const T & val) { write_str(key); @@ -155,6 +146,7 @@ struct gguf_file { fwrite((const char *) &n, sizeof(n), 1, fp); fwrite(val.data(), sizeof(T), n, fp); } + template<> void write_val(const std::string & key, enum gguf_type type, const std::string & val) { write_str(key); @@ -188,6 +180,37 @@ struct gguf_file { fputc(0, fp); } } + + void read_raw(void * ptr, size_t len) const { + if (len == 0) { + return; + } + errno = 0; + std::size_t ret = std::fread(ptr, len, 1, fp); + if (ferror(fp)) { + throw std::runtime_error(format("read error: %s", strerror(errno))); + } + if (ret != 1) { + throw std::runtime_error(std::string("unexpectedly reached end of file")); + } + } + + void write_raw(const void * ptr, size_t len) const { + if (len == 0) { + return; + } + errno = 0; + size_t ret = std::fwrite(ptr, len, 1, fp); + if (ret != 1) { + throw std::runtime_error(format("write error: %s", strerror(errno))); + } + } + + ~gguf_file() { + if (fp) { + std::fclose(fp); + } + } }; #if defined(_WIN32)