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 "io_utils.h"
#define _READFILE_GUESS 512
void combine(char* destination, const char* path1, const char* path2) {
if(path1 == NULL || path2 == NULL) {
strcpy(destination, "");
@ -43,36 +41,30 @@ const char *get_filename_ext(const char *filename) {
}
char *read_file(char *name){
FILE* file;
file = fopen(name, "r");
char *result = NULL;
FILE *file = fopen(name, "r");
if (file != NULL) {
// Go to end of ile
if (fseek(file, 0L, SEEK_END) == 0) {
if(!file)
return NULL;
// get size of file
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)
return NULL;
// go back to start of file
if (fseek(file, 0L, SEEK_SET) != 0) { return NULL; }
size_t pos = 0;
size_t capacity = _READFILE_GUESS;
char ch;
while((ch = getc(file)) != EOF){
result[pos++] = ch;
if(pos >= capacity){
capacity += _READFILE_GUESS;
result = realloc(result, sizeof(char) * capacity + 1);
if(result == NULL)
return NULL;
// read file into memory
size_t newLen = fread(result, sizeof(char), bufsize, file);
if ( ferror( file ) != 0 ) { return NULL; }
else {
result[newLen++] = '\0'; // just to be safe
}
}
fclose(file);
result = realloc(result, sizeof(char) * pos);
if(result == NULL)
return NULL;
result[pos] = '\0';
}
return result;
}