file.h (1080B)
1 #pragma once 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 #include "utils.h" 7 8 char* readfile(const char* file_path) 9 { 10 FILE* fp = fopen(file_path, "rb"); 11 if (fp == NULL) { 12 perror("Failed to read file"); 13 return NULL; 14 } 15 16 if (fseek(fp, 0, SEEK_END) != 0) { 17 fclose(fp); 18 panic("Failed to find the end of the file"); 19 return NULL; 20 } 21 22 long file_size = ftell(fp); 23 24 if (file_size < 0) { 25 fclose(fp); 26 panic("Failed to determine the file size"); 27 return NULL; 28 } 29 30 rewind(fp); 31 32 // check for overflow before casting 33 if ((unsigned long)file_size >= SIZE_MAX) { 34 fclose(fp); 35 panic("File too large to fit in memory"); 36 return NULL; 37 } 38 39 char* contents = (char*)calloc(1, (size_t)file_size + 1); 40 if (contents == NULL) { 41 panic("Failed to allocate memory to read file"); 42 fclose(fp); 43 return NULL; 44 } 45 46 size_t bytes_read = fread(contents, 1, (size_t)file_size, fp); 47 if (bytes_read != (size_t)file_size) { 48 free(contents); 49 fclose(fp); 50 panic("Failed to read the file in its entirety"); 51 return NULL; 52 } 53 54 contents[file_size] = '\0'; 55 56 fclose(fp); 57 return contents; 58 }