42 lines
1 KiB
C
42 lines
1 KiB
C
#include "../lib/io.h"
|
|
|
|
bool read_file(const char* path, uint8_t** data, 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 false;
|
|
}
|
|
|
|
struct stat statOfFile;
|
|
int status = fstat(fileno(f), &statOfFile);
|
|
if (status == -1) {
|
|
printf("Fstat error: %d\n", errno);
|
|
fclose(f);
|
|
return false;
|
|
};
|
|
|
|
if ((statOfFile.st_mode & S_IFMT) != S_IFREG) {
|
|
printf("File is not a regular file!\n");
|
|
fclose(f);
|
|
return false;
|
|
}
|
|
|
|
(*data) = malloc(statOfFile.st_size);
|
|
|
|
size_t bytesRead =
|
|
fread((*data), statOfFile.st_blksize, statOfFile.st_blocks, f);
|
|
// size_t bytesRead = fread(data, sizeof(uint8_t), statOfFile.st_size, f);
|
|
if (bytesRead != 0 && !feof(f)) {
|
|
printf("Error reading file!\n");
|
|
fclose(f);
|
|
return false;
|
|
}
|
|
|
|
fclose(f);
|
|
|
|
(*size) = statOfFile.st_size;
|
|
return true;
|
|
} |