gra-projekt/Implementierung/src/io.c

62 lines
1.4 KiB
C
Raw Normal View History

2022-06-29 21:29:15 +02:00
#include "../lib/io.h"
2022-06-29 10:58:49 +02:00
2022-07-12 22:33:01 +02:00
bool open_file(const char* path, FILE** file, struct stat* file_stat) {
(*file) = fopen(path, "r");
if ((*file) == NULL) {
if (errno == 0) errno = EIO;
2022-07-12 22:33:01 +02:00
return false;
2022-06-29 11:12:35 +02:00
}
2022-06-29 10:58:49 +02:00
2022-07-12 22:33:01 +02:00
int status = fstat(fileno((*file)), file_stat);
2022-06-29 11:12:35 +02:00
if (status == -1) {
if (errno == 0) errno = EIO;
2022-07-12 22:33:01 +02:00
fclose((*file));
return false;
2022-06-29 11:12:35 +02:00
};
2022-06-29 10:58:49 +02:00
2022-07-12 22:33:01 +02:00
if ((file_stat->st_mode & S_IFMT) != S_IFREG) {
2022-06-29 11:12:35 +02:00
printf("File is not a regular file!\n");
errno = ENOENT;
2022-07-12 22:33:01 +02:00
fclose((*file));
return false;
}
return true;
}
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;
struct stat statOfFile;
if (!open_file(path, &f, &statOfFile)) {
2022-06-29 22:02:18 +02:00
return NULL;
2022-06-29 11:12:35 +02:00
}
2022-06-29 10:58:49 +02:00
struct sysinfo info;
int r = sysinfo(&info);
if (r != 0 || info.freeram < (unsigned long)statOfFile.st_size * 2) {
errno = ENOMEM;
return NULL;
}
2022-06-29 22:02:18 +02:00
uint8_t* data = malloc(statOfFile.st_size);
if (data == NULL) {
fclose(f);
return NULL;
}
2022-06-29 10:58:49 +02:00
2022-06-29 11:12:35 +02:00
size_t bytesRead =
2022-06-29 22:02:18 +02:00
fread(data, statOfFile.st_blksize, statOfFile.st_blocks, f);
2022-06-29 20:54:41 +02:00
// size_t bytesRead = fread(data, sizeof(uint8_t), statOfFile.st_size, f);
2022-06-29 11:12:35 +02:00
if (bytesRead != 0 && !feof(f)) {
2022-06-29 10:58:49 +02:00
fclose(f);
if (errno == 0) errno = EIO;
2022-06-29 22:02:18 +02:00
return NULL;
2022-06-29 11:12:35 +02:00
}
fclose(f);
2022-06-29 10:58:49 +02:00
2022-06-29 20:54:41 +02:00
(*size) = statOfFile.st_size;
2022-06-29 22:02:18 +02:00
return data;
2022-06-29 10:58:49 +02:00
}