Improved read_file function (fixes minor memory leak and should speed things up as more languages are added)

This commit is contained in:
GammaTendonNine 2020-10-21 17:41:55 -05:00
parent 75e0a1e826
commit 2086385691
1 changed files with 21 additions and 29 deletions

View File

@ -5,8 +5,6 @@
#include <limits.h> #include <limits.h>
#include "io_utils.h" #include "io_utils.h"
#define _READFILE_GUESS 512
void combine(char* destination, const char* path1, const char* path2) { void combine(char* destination, const char* path1, const char* path2) {
if(path1 == NULL || path2 == NULL) { if(path1 == NULL || path2 == NULL) {
strcpy(destination, ""); strcpy(destination, "");
@ -42,37 +40,31 @@ const char *get_filename_ext(const char *filename) {
return dot + 1; return dot + 1;
} }
char* read_file(char* name){ char *read_file(char *name){
FILE* file; char *result = NULL;
file = fopen(name, "r"); FILE *file = fopen(name, "r");
if (file != NULL) {
// Go to end of ile
if (fseek(file, 0L, SEEK_END) == 0) {
if(!file) // get size of file
return NULL; long bufsize = ftell(file);
if (bufsize == -1) { return NULL; }
char* result = malloc(sizeof(char) * _READFILE_GUESS + 1); // allocate buzzer to size
result = malloc(sizeof(char) * (bufsize + 1));
if(result == NULL) // go back to start of file
return NULL; if (fseek(file, 0L, SEEK_SET) != 0) { return NULL; }
size_t pos = 0; // read file into memory
size_t capacity = _READFILE_GUESS; size_t newLen = fread(result, sizeof(char), bufsize, file);
char ch; if ( ferror( file ) != 0 ) { return NULL; }
else {
while((ch = getc(file)) != EOF){ result[newLen++] = '\0'; // just to be safe
result[pos++] = ch; }
if(pos >= capacity){
capacity += _READFILE_GUESS;
result = realloc(result, sizeof(char) * capacity + 1);
if(result == NULL)
return NULL;
} }
fclose(file);
} }
fclose(file);
result = realloc(result, sizeof(char) * pos);
if(result == NULL)
return NULL;
result[pos] = '\0';
return result; return result;
} }