#include "file.h" #include #include #include #include #include char *read_file(const char *path) { create_file_if_not_exists(path); FILE *fp = fopen(path, "rb"); if (fp == NULL) { perror("Error opening file"); return nullptr; } fseek(fp, 0, SEEK_END); long file_size = ftell(fp); rewind(fp); char *buffer = (char *) malloc(file_size + 1); if (!buffer) { perror("Error allocating memory"); fclose(fp); return nullptr; } size_t bytes_read = fread(buffer, 1, file_size, fp); if (bytes_read != file_size) { perror("Error reading file"); free(buffer); fclose(fp); return nullptr; } buffer[file_size] = '\0'; fclose(fp); return buffer; } char *write_file(const char *path, const char *data) { create_file_if_not_exists(path); FILE *fp = fopen(path, "w"); if (fp == NULL) { printf("%s\n", path); perror("Error opening file"); return nullptr; } if (fprintf(fp, "%s", data) < 0) { perror("Error write file"); return nullptr; } fclose(fp); char *ret = strdup(data); return ret; } int create_file_if_not_exists(const char *filename) { if (!check_file_exists(filename)) { return 0; } FILE *file = fopen(filename, "w"); if (file == nullptr) { perror("Error creating file"); return -1; } fclose(file); return 0; } int check_file_exists(const char *filename) { if (access(filename, F_OK) == 0) { return 0; } return -1; }