ox

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

file.h (1080B)



#pragma once

#include <stdio.h>
#include <stdlib.h>

#include "utils.h"

char*
readfile(const char* file_path)
{
	FILE* fp = fopen(file_path, "rb");
	if (fp == NULL) {
		perror("Failed to read file");
		return NULL;
	}

	if (fseek(fp, 0, SEEK_END) != 0) {
		fclose(fp);
		panic("Failed to find the end of the file");
		return NULL;
	}

	long file_size = ftell(fp);

	if (file_size < 0) {
		fclose(fp);
		panic("Failed to determine the file size");
		return NULL;
	}

	rewind(fp);

	// check for overflow before casting
	if ((unsigned long)file_size >= SIZE_MAX) {
		fclose(fp);
		panic("File too large to fit in memory");
		return NULL;
	}

	char* contents = (char*)calloc(1, (size_t)file_size + 1);
	if (contents == NULL) {
		panic("Failed to allocate memory to read file");
		fclose(fp);
		return NULL;
	}

	size_t bytes_read = fread(contents, 1, (size_t)file_size, fp);
	if (bytes_read != (size_t)file_size) {
		free(contents);
		fclose(fp);
		panic("Failed to read the file in its entirety");
		return NULL;
	}

	contents[file_size] = '\0';

	fclose(fp);
	return contents;
}