feat(file): implemented file reading/writting #11

Merged
Mineplay merged 30 commits from feat/4-file into main 2025-12-21 06:12:09 -06:00
Showing only changes of commit 6a5a80b3f5 - Show all commits

View file

@ -47,15 +47,22 @@ CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned l
}
*size = file_stat.st_size;
*content = (char*)malloc(file_stat.st_size * sizeof(char));
*content = (char*)malloc((file_stat.st_size + 1) * sizeof(char));
if (content == NULL) {
close(file);
return COSMS_FILE_FAILED_TO_ALLOCATE;
}
unsigned int remaining_bytes = file_stat.st_size;
unsigned long long remaining_bytes = file_stat.st_size;
while (remaining_bytes != 0) {
int read_bytes = read(file, (*content) + (file_stat.st_size - remaining_bytes), remaining_bytes);
unsigned int bytes_to_read;
if (remaining_bytes > UINT_MAX) {
bytes_to_read = UINT_MAX;
} else {
bytes_to_read = (unsigned int)remaining_bytes;
}
int read_bytes = read(file, (*content) + (file_stat.st_size - remaining_bytes), bytes_to_read);
if (read_bytes == -1) {
free(*content);
close(file);
@ -65,6 +72,7 @@ CosmsFileError cosms_core_file_read(const char *path, char **content, unsigned l
remaining_bytes -= read_bytes;
}
(*content)[file_stat.st_size] = '\0';
close(file);
#elif defined(_WIN32)
HANDLE file = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
@ -154,9 +162,16 @@ CosmsFileError cosms_core_file_write(const char *path, const char *content, unsi
}
}
unsigned int remaining_bytes = size;
unsigned long long remaining_bytes = size;
while (remaining_bytes != 0) {
int written_bytes = write(file, content + (size - remaining_bytes), remaining_bytes);
unsigned int bytes_to_write;
if (remaining_bytes > UINT_MAX) {
bytes_to_write = UINT_MAX;
} else {
bytes_to_write = (unsigned int)remaining_bytes;
}
int written_bytes = write(file, content + (size - remaining_bytes), bytes_to_write);
if (written_bytes == -1) {
close(file);
return COSMS_FILE_FAILED_TO_WRITE;