diff options
author | Campbell Barton <ideasman42@gmail.com> | 2015-12-14 09:12:16 +0300 |
---|---|---|
committer | Campbell Barton <ideasman42@gmail.com> | 2015-12-14 09:16:23 +0300 |
commit | de0119d087acb4e38488d6f472fb7d4f0de26c17 (patch) | |
tree | c33c7a83d87546590c8029fddef14695cb89eb7b /source/blender/blenlib | |
parent | 4510fe82aaa1e60a82726d981a9a21ee4866ec7a (diff) |
BLI_storage: util function BLI_file_read_as_mem
Use for text loading and pasting from file.
Diffstat (limited to 'source/blender/blenlib')
-rw-r--r-- | source/blender/blenlib/BLI_fileops.h | 1 | ||||
-rw-r--r-- | source/blender/blenlib/intern/storage.c | 33 |
2 files changed, 34 insertions, 0 deletions
diff --git a/source/blender/blenlib/BLI_fileops.h b/source/blender/blenlib/BLI_fileops.h index 53ebc81fe22..b842c30c975 100644 --- a/source/blender/blenlib/BLI_fileops.h +++ b/source/blender/blenlib/BLI_fileops.h @@ -130,6 +130,7 @@ bool BLI_file_older(const char *file1, const char *file2) ATTR_WARN_UNUSED_RES /* read ascii file as lines, empty list if reading fails */ struct LinkNode *BLI_file_read_as_lines(const char *file) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(); +void *BLI_file_read_as_mem(const char *filepath, size_t pad_bytes, size_t *r_size); void BLI_file_free_lines(struct LinkNode *lines); /* this weirdo pops up in two places ... */ diff --git a/source/blender/blenlib/intern/storage.c b/source/blender/blenlib/intern/storage.c index f7a8664c739..a107c84d4d0 100644 --- a/source/blender/blenlib/intern/storage.c +++ b/source/blender/blenlib/intern/storage.c @@ -287,6 +287,39 @@ bool BLI_is_file(const char *path) return (mode && !S_ISDIR(mode)); } +void *BLI_file_read_as_mem(const char *filepath, size_t pad_bytes, size_t *r_size) +{ + FILE *fp = BLI_fopen(filepath, "r"); + void *mem = NULL; + + if (fp) { + fseek(fp, 0L, SEEK_END); + const long int filelen = ftell(fp); + if (filelen == -1) { + goto finally; + } + fseek(fp, 0L, SEEK_SET); + + mem = MEM_mallocN(filelen + pad_bytes, __func__); + if (mem == NULL) { + goto finally; + } + + if (fread(mem, 1, filelen, fp) != filelen) { + MEM_freeN(mem); + mem = NULL; + goto finally; + } + + *r_size = filelen; + } + +finally: + fclose(fp); + return mem; +} + + /** * Reads the contents of a text file and returns the lines in a linked list. */ |