sic

The sic programming language, compiler and tools (WIP)
Log | Files | Refs

utils.c (1221B)



#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* read_file(const char* filename)
{
    long fsize;
    char* source;
    FILE* fp = fopen(filename, "rb");
    if (fp == NULL) {
        fprintf(stderr, "file not found\n");
        return NULL;
    }

    if (fseek(fp, 0, SEEK_END) != 0) {
        fprintf(stderr, "could not read file\n");
        fclose(fp);
        exit(1);
    }

    fsize = ftell(fp);
    if (fsize < 0) {
        fprintf(stderr, "could not read size of file to load\n");
        fclose(fp);
        exit(1);
    }
    fseek(fp, 0, SEEK_SET);

    source = malloc(fsize + 1);
    if (!source) {
        fprintf(stderr, "could not allocate memory to read file\n");
        exit(1);
    }
    fread(source, fsize, 1, fp);
    fclose(fp);

    source[fsize] = '\0';
    return source;
}

void separate_file_from_path(const char* fullpath, char** out_path, char** out_filename)
{
    char* path = strdup(fullpath);
    char* filename = strrchr(path, '/');

    if (filename == NULL) {
        printf("No path found\n");
        exit(1);
    }

    *filename = '\0';
    filename++;
    *out_path = strdup(path);
    *out_filename = strdup(filename);
    free(path);
}