From 66ab9fbbdf61730cc237c566ccc2e89813b8a19d Mon Sep 17 00:00:00 2001 From: Mineplay Date: Fri, 5 Dec 2025 20:05:14 +0100 Subject: [PATCH] feat(file): implemented write file for linux --- include/cosms-core/file.h | 1 + src/file.c | 43 ++++++++++++++++++++++++++++++++++++++- tests/main.c | 8 ++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/include/cosms-core/file.h b/include/cosms-core/file.h index 2a25de2..f609ff4 100644 --- a/include/cosms-core/file.h +++ b/include/cosms-core/file.h @@ -20,6 +20,7 @@ typedef enum { COSMS_FILE_UNKOWN_ERROR = -5, COSMS_FILE_FAILED_TO_ALLOCATE = -6, COSMS_FILE_FAILED_TO_READ = -7, + COSMS_FILE_FAILED_TO_WRITE = -8, } CosmsFileError; CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned int *size); diff --git a/src/file.c b/src/file.c index 2b7b53f..b3673af 100644 --- a/src/file.c +++ b/src/file.c @@ -53,7 +53,7 @@ CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned i unsigned int remaining_bytes = file_stat.st_size; while (remaining_bytes != 0) { - int read_bytes = read(file, *content, remaining_bytes); + int read_bytes = read(file, (*content) + (file_stat.st_size - remaining_bytes), remaining_bytes); if (read_bytes == -1) { free(content); close(file); @@ -66,9 +66,50 @@ CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned i close(file); #elif defined(_WIN32) #endif + return COSMS_FILE_OK; } CosmsFileError cosms_core_file_write(const char *path, const char *content, unsigned int size, bool override) { + #if defined(__GNUC__) + int file; + if (override) { + file = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + } else { + file = open(path, O_WRONLY | O_APPEND); + } + + 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; + } + } + + unsigned int remaining_bytes = size; + while (remaining_bytes != 0) { + int written_bytes = write(file, content + (size - remaining_bytes), remaining_bytes); + if (written_bytes == -1) { + close(file); + return COSMS_FILE_FAILED_TO_WRITE; + } + + remaining_bytes -= written_bytes; + } + + close(file); + #elif defined(_WIN32) + #endif + return COSMS_FILE_OK; } diff --git a/tests/main.c b/tests/main.c index c0c30cb..b63a90b 100644 --- a/tests/main.c +++ b/tests/main.c @@ -12,5 +12,13 @@ int main(void) { } printf("File read with content:\n %s\n", buffer); + + char *temp_buffer = "Hello, World!"; + error = cosms_core_file_write("write-file.txt", temp_buffer, 13, true); + if (error != COSMS_FILE_OK) { + fprintf(stderr, "failed to write file exited with error code: %d\n", error); + return -1; + } + return 0; }