feat(file): implemented write file for linux

This commit is contained in:
Mineplay 2025-12-05 20:05:14 +01:00
parent 531a4d03cb
commit 66ab9fbbdf
3 changed files with 51 additions and 1 deletions

View file

@ -20,6 +20,7 @@ typedef enum {
COSMS_FILE_UNKOWN_ERROR = -5, COSMS_FILE_UNKOWN_ERROR = -5,
COSMS_FILE_FAILED_TO_ALLOCATE = -6, COSMS_FILE_FAILED_TO_ALLOCATE = -6,
COSMS_FILE_FAILED_TO_READ = -7, COSMS_FILE_FAILED_TO_READ = -7,
COSMS_FILE_FAILED_TO_WRITE = -8,
} CosmsFileError; } CosmsFileError;
CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned int *size); CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned int *size);

View file

@ -53,7 +53,7 @@ CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned i
unsigned int remaining_bytes = file_stat.st_size; unsigned int remaining_bytes = file_stat.st_size;
while (remaining_bytes != 0) { 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) { if (read_bytes == -1) {
free(content); free(content);
close(file); close(file);
@ -66,9 +66,50 @@ CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned i
close(file); close(file);
#elif defined(_WIN32) #elif defined(_WIN32)
#endif #endif
return COSMS_FILE_OK; return COSMS_FILE_OK;
} }
CosmsFileError cosms_core_file_write(const char *path, const char *content, unsigned int size, bool override) { 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; return COSMS_FILE_OK;
} }

View file

@ -12,5 +12,13 @@ int main(void) {
} }
printf("File read with content:\n %s\n", buffer); 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; return 0;
} }