Last active
May 4, 2020 19:37
-
-
Save bit-hack/7208f11d6ea02ddbe05cb36c1c816174 to your computer and use it in GitHub Desktop.
Simple file loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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