Skip to content

Instantly share code, notes, and snippets.

@bit-hack
Last active May 4, 2020 19:37
Show Gist options
  • Save bit-hack/7208f11d6ea02ddbe05cb36c1c816174 to your computer and use it in GitHub Desktop.
Save bit-hack/7208f11d6ea02ddbe05cb36c1c816174 to your computer and use it in GitHub Desktop.
Simple file loader
#include <stdio.h>
#include <stdlib.h>
#include "file.h"
bool file_load(const char *path, file_t *out) {
if (out->data) {
file_unload(out);
}
FILE *fd = fopen(path, "rb");
if (!fd) {
return false;
}
fseek(fd, 0, SEEK_END);
out->size = ftell(fd);
fseek(fd, 0, SEEK_SET);
if (out->size == 0) {
fclose(fd);
return false;
}
out->data = malloc(out->size);
if (out->data == NULL) {
fclose(fd);
return false;
}
const size_t read = fread(out->data, 1, out->size, fd);
fclose(fd);
if (read != out->size) {
file_unload(out);
return false;
}
return true;
}
void file_unload(file_t *out) {
if (out->data) {
free(out->data);
out->data = NULL;
}
out->size = 0;
}
#pragma once
#include <stdbool.h>
#include <stdint.h>
typedef struct {
uint8_t *data;
uint32_t size;
} file_t;
bool file_load(const char *path, file_t *out);
void file_unload(file_t *out);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment