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


// Reads an entire text file into a buffer. 
// USES MALLOC BE SURE TO FREE
char* readTextFile(char* fname)
{
    FILE* inFile;
    long fileLength;
    char* fileBuffer;
    size_t result;

    inFile = fopen( fname, "rb" );
    if( inFile == NULL )
    {
        fprintf( stderr, "Failed open file, [%s].\n", fname );
        exit(1);
    }

    fseek( inFile, 0, SEEK_END );
    fileLength = ftell( inFile );
    printf("File length: %d\n", fileLength);
    rewind( inFile );
    
    fileBuffer = (char*) malloc(sizeof(char) * (fileLength + 1));
    if( fileBuffer == NULL )
    {
        fprintf( stderr, "Failed to allocate memory for reading the file, [%s].\n", fname);
        exit(2);
    }

    result = fread( fileBuffer, 1, fileLength, inFile );
    if( result != fileLength )
    {
        free( fileBuffer );
        fprintf( stderr, "Failed while reading [%s] into the file buffer.\n", fname);
        exit(3);
    }

    fileBuffer[fileLength] = '\0';

    fclose( inFile );

    return fileBuffer;
}
