From 60271422194afae4a9c89dceaed5c2d53c51ff00 Mon Sep 17 00:00:00 2001 From: Joursoir Date: Sat, 3 Apr 2021 17:56:02 +0000 Subject: add routine for read file --- src/xstdlib/xstdlib.cpp | 38 ++++++++++++++++++++++++++++++++++++++ src/xstdlib/xstdlib.hpp | 6 ++++++ 2 files changed, 44 insertions(+) create mode 100644 src/xstdlib/xstdlib.cpp create mode 100644 src/xstdlib/xstdlib.hpp diff --git a/src/xstdlib/xstdlib.cpp b/src/xstdlib/xstdlib.cpp new file mode 100644 index 0000000..4264e68 --- /dev/null +++ b/src/xstdlib/xstdlib.cpp @@ -0,0 +1,38 @@ +#include + +#include "xstdlib.hpp" + +char *xfread(const char *path, const char *mode) +{ + char *source = 0; + size_t file_size, bytes_read; + FILE *file; + + file = fopen(path, mode); + if(!file) + return 0; + + do { + if(fseek(file, 0, SEEK_END) < 0) + break; + + file_size = ftell(file); + if(file_size < 0) + break; + + if(fseek(file, 0, SEEK_SET) < 0) + break; + + source = new char[file_size + 1]; + bytes_read = fread(source, 1, file_size, file); + if(bytes_read != file_size) { + delete[] source; + source = 0; + } + source[file_size] = '\0'; + } while(0); + + fclose(file); + return source; +} + diff --git a/src/xstdlib/xstdlib.hpp b/src/xstdlib/xstdlib.hpp new file mode 100644 index 0000000..7a2c704 --- /dev/null +++ b/src/xstdlib/xstdlib.hpp @@ -0,0 +1,6 @@ +#ifndef ENGINE_XSTDLIB_H +#define ENGINE_XSTDLIB_H + +char *xfread(const char *path, const char *mode); + +#endif /* ENGINE_XSTDLIB_H */ -- cgit v1.2.3-18-g5258