From c28a7d2e3e91db98028a3238daf5e15f1a2c6103 Mon Sep 17 00:00:00 2001 From: kramm Date: Fri, 19 Dec 2008 08:05:26 +0000 Subject: [PATCH] added memfile --- lib/os.c | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ lib/os.h | 7 +++++++ 2 files changed, 75 insertions(+) diff --git a/lib/os.c b/lib/os.c index c768513..8ba360a 100755 --- a/lib/os.c +++ b/lib/os.c @@ -26,6 +26,24 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include #ifdef WIN32 #include +#else +#include +#include +#endif +#ifdef HAVE_SYS_STAT_H +#include +#else +#undef HAVE_STAT +#endif +#ifdef HAVE_SYS_MMAN_H +#include +#else +#undef HAVE_MMAP +#endif +#ifdef HAVE_SYS_TYPES_H +#include +#else +#undef HAVE_STAT #endif #if defined(CYGWIN) @@ -205,3 +223,53 @@ char* mktempname(char*ptr) { return ptr; } +memfile_t* memfile_open(const char*path) +{ + memfile_t*file = malloc(sizeof(memfile_t)); +#if defined(HAVE_MMAP) && defined(HAVE_STAT) + int fi = open(path, O_RDONLY); + if(fi<0) { + perror(path); + free(file); + return 0; + } + struct stat sb; + if(fstat(fi, &sb)<0) { + perror(path); + return 0; + } + file->len = sb.st_size; + file->data = mmap(0, sb.st_size, PROT_READ, MAP_PRIVATE, fi, 0); +#else + FILE*fi = fopen(path, "rb"); + if(!fi) { + perror(path); + free(file); + return 0; + } + fseek(fi, 0, SEEK_END); + file->len = ftell(fi); + fseek(fi, 0, SEEK_SET); + file->data = malloc(file->len); + if(!file->data) { + fprintf(stderr, "Out of memory while allocating memory for file %s\n", path); + free(file); + return 0; + } + fread(file->data, file->len, 1, fi); + fclose(fi); +#endif + return file; +} + +void memfile_close(memfile_t*file) +{ +#if defined(HAVE_MMAP) && defined(HAVE_STAT) + munmap(file->data, file->len); +#else + free(file->data); +#endif + file->data = file->len = 0; + free(file); +} + diff --git a/lib/os.h b/lib/os.h index 67736fc..7aadc2f 100755 --- a/lib/os.h +++ b/lib/os.h @@ -34,6 +34,13 @@ char* getRegistryEntry(char*path); int setRegistryEntry(char*key,char*value); #endif +typedef struct _memfile { + void*data; + int len; +} memfile_t; +memfile_t* memfile_open(const char*path); +void memfile_close(memfile_t*file); + char* getInstallationPath(); char* concatPaths(const char*base, const char*add); char* stripFilename(const char*filename, const char*newext); -- 1.7.10.4