gra-projekt/Implementierung/src/io.c

80 lines
1.6 KiB
C

#include "../lib/io.h"
bool open_file(const char* path, FILE** file, struct stat* file_stat) {
(*file) = fopen(path, "r");
if ((*file) == NULL) {
if (errno == 0) errno = EIO;
return false;
}
int status = fstat(fileno((*file)), file_stat);
if (status == -1) {
if (errno == 0) errno = EIO;
fclose((*file));
return false;
};
if ((file_stat->st_mode & S_IFMT) != S_IFREG) {
printf("File is not a regular file!\n");
errno = ENOENT;
fclose((*file));
return false;
}
return true;
}
unsigned long get_available_memory() {
FILE* f;
struct stat statOfFile;
if (!open_file("/proc/meminfo", &f, &statOfFile)) {
return 0;
}
char line[100];
while (fgets(line, sizeof(line), f)) {
unsigned long available_memory;
if (sscanf(line, "MemAvailable: %ld kB", &available_memory) == 1) {
fclose(f);
return available_memory * 1000;
}
}
return 0;
}
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)) {
return NULL;
}
unsigned long available_memory = get_available_memory();
if (available_memory < (unsigned long)(statOfFile.st_size * 2)) {
errno = ENOMEM;
return NULL;
}
uint8_t* data = malloc(statOfFile.st_size);
if (data == NULL) {
fclose(f);
return NULL;
}
fread(data, 1, statOfFile.st_size, f);
if (ferror(f)) {
fclose(f);
if (errno == 0) errno = EIO;
return NULL;
}
fclose(f);
(*size) = statOfFile.st_size;
return data;
}