41 lines
1.1 KiB
C
41 lines
1.1 KiB
C
|
#include "io.h"
|
||
|
|
||
|
static uint8_t* read_file(const char* path, size_t* size) {
|
||
|
// Read the contents of the file specified by path into a heap-allocated
|
||
|
// buffer and return a pointer to that buffer.
|
||
|
FILE* f = fopen(path, "r");
|
||
|
if(f == NULL) {
|
||
|
printf("Fopen error: %d\n", errno);
|
||
|
fclose(f);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
struct stat statOfFile;
|
||
|
int status = fstat(fileno(f), &statOfFile);
|
||
|
if(status == -1) {
|
||
|
printf("Fstat error: %d\n", errno);
|
||
|
fclose(f);
|
||
|
return NULL;
|
||
|
};
|
||
|
|
||
|
if((statOfFile.st_mode & S_IFMT) != S_IFREG){
|
||
|
printf("File is not a regular file!\n");
|
||
|
fclose(f);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
uint8_t* data = malloc(statOfFile.st_size);
|
||
|
|
||
|
size_t bytesRead = fread(data, statOfFile.st_blksize, statOfFile.st_blocks, f);
|
||
|
// Or: size_t bytesRead = fread(data, sizeof(char), statOfFile.st_size, f);
|
||
|
if(bytesRead != 0 && !feof(f)) {
|
||
|
printf("Error reading file!\n");
|
||
|
fclose(f);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
fclose(f);
|
||
|
|
||
|
(*size) = bytesRead;
|
||
|
return data;
|
||
|
}
|