gra-projekt/Implementierung/src/io.c

42 lines
1,000 B
C
Raw Normal View History

2022-06-29 10:58:49 +02:00
#include "io.h"
2022-06-29 19:03:12 +02:00
uint8_t* read_file(const char* path, size_t* size) {
2022-06-29 11:12:35 +02:00
// 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;
}
2022-06-29 10:58:49 +02:00
2022-06-29 11:12:35 +02:00
struct stat statOfFile;
int status = fstat(fileno(f), &statOfFile);
if (status == -1) {
printf("Fstat error: %d\n", errno);
fclose(f);
return NULL;
};
2022-06-29 10:58:49 +02:00
2022-06-29 11:12:35 +02:00
if ((statOfFile.st_mode & S_IFMT) != S_IFREG) {
printf("File is not a regular file!\n");
fclose(f);
return NULL;
}
2022-06-29 10:58:49 +02:00
2022-06-29 11:12:35 +02:00
uint8_t* data = malloc(statOfFile.st_size);
2022-06-29 10:58:49 +02:00
2022-06-29 11:12:35 +02:00
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");
2022-06-29 10:58:49 +02:00
fclose(f);
2022-06-29 11:12:35 +02:00
return NULL;
}
fclose(f);
2022-06-29 10:58:49 +02:00
2022-06-29 11:12:35 +02:00
(*size) = bytesRead;
return data;
2022-06-29 10:58:49 +02:00
}