ox

The Ox programming language, compiler and tools (WIP)
Log | Files | Refs | README | LICENSE

file.h (1080B)


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