diff --git a/include/cosms-core/file.h b/include/cosms-core/file.h index 4a0c4ae..2a25de2 100644 --- a/include/cosms-core/file.h +++ b/include/cosms-core/file.h @@ -9,12 +9,20 @@ #ifndef COSMS_CORE_FILE #define COSMS_CORE_FILE +#include + typedef enum { COSMS_FILE_OK = 0, COSMS_FILE_NOT_FOUND = -1, + COSMS_FILE_NO_ACCESS = -2, + COSMS_FILE_LIMIT_REACHED = -3, + COSMS_FILE_COULD_NOT_READ_SIZE = -4, + COSMS_FILE_UNKOWN_ERROR = -5, + COSMS_FILE_FAILED_TO_ALLOCATE = -6, + COSMS_FILE_FAILED_TO_READ = -7, } CosmsFileError; -CosmsFileError cosms_core_file_read(char *path); -CosmsFileError cosms_core_file_write(char *path); +CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned int *size); +CosmsFileError cosms_core_file_write(const char *path, const char *content, unsigned int size, bool override); #endif diff --git a/src/file.c b/src/file.c index d7660d4..2b7b53f 100644 --- a/src/file.c +++ b/src/file.c @@ -8,14 +8,67 @@ */ #include "cosms-core/file.h" -#include +#include -CosmsFileError cosms_core_file_read(char *path) { - printf("Hello, World!"); +#if defined(__GNUC__) +#include +#include +#include +#include +#elif defined(_WIN32) +#endif + +CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned int *size) { + #if defined(__GNUC__) + int file = open(path, O_RDONLY); + if (file == -1) { + switch(errno) { + case ENOENT: + return COSMS_FILE_NOT_FOUND; + + case EACCES: + return COSMS_FILE_NO_ACCESS; + + case EMFILE: + case ENFILE: + return COSMS_FILE_LIMIT_REACHED; + + default: + return COSMS_FILE_UNKOWN_ERROR; + } + } + + struct stat file_stat; + if (stat(path, &file_stat) != 0) { + close(file); + return COSMS_FILE_COULD_NOT_READ_SIZE; + } + + *size = file_stat.st_size; + *content = (char*)malloc(file_stat.st_size * sizeof(char)); + if (content == NULL) { + close(file); + return COSMS_FILE_FAILED_TO_ALLOCATE; + } + + unsigned int remaining_bytes = file_stat.st_size; + while (remaining_bytes != 0) { + int read_bytes = read(file, *content, remaining_bytes); + if (read_bytes == -1) { + free(content); + close(file); + return COSMS_FILE_FAILED_TO_READ; + } + + remaining_bytes -= read_bytes; + } + + close(file); + #elif defined(_WIN32) + #endif return COSMS_FILE_OK; } -CosmsFileError cosms_core_file_write(char *path) { - printf("Hello, World"); +CosmsFileError cosms_core_file_write(const char *path, const char *content, unsigned int size, bool override) { return COSMS_FILE_OK; } diff --git a/tests/main.c b/tests/main.c index e6e6793..c0c30cb 100644 --- a/tests/main.c +++ b/tests/main.c @@ -1,6 +1,16 @@ #include +#include + int main(void) { - cosms_core_file_read("test.txt"); + unsigned int buffer_size; + char *buffer; + CosmsFileError error = cosms_core_file_read("test.txt", &buffer, &buffer_size); + if (error != COSMS_FILE_OK) { + fprintf(stderr, "failed to read file exited with error code: %d\n", error); + return -1; + } + + printf("File read with content:\n %s\n", buffer); return 0; }