From de97bedc003f54fe185c0939d45368503e0b5169 Mon Sep 17 00:00:00 2001 From: Mateusz Faderewski Date: Sun, 20 Aug 2023 17:54:37 +0200 Subject: [PATCH] Improved empty save compatibility by filling initial save with 0xFF --- src/flashcart/flashcart.c | 3 +++ src/utils/fs.c | 36 ++++++++++++++++++++++++++++++++++++ src/utils/fs.h | 1 + 3 files changed, 40 insertions(+) diff --git a/src/flashcart/flashcart.c b/src/flashcart/flashcart.c index 0571360c..0b241421 100644 --- a/src/flashcart/flashcart.c +++ b/src/flashcart/flashcart.c @@ -140,6 +140,9 @@ flashcart_error_t flashcart_load_save (char *save_path, flashcart_save_type_t sa if (file_allocate(save_path, SAVE_SIZE[save_type])) { return FLASHCART_ERROR_LOAD; } + if (file_fill(save_path, 0xFF)) { + return FLASHCART_ERROR_LOAD; + } } if (file_get_size(save_path) != SAVE_SIZE[save_type]) { diff --git a/src/utils/fs.c b/src/utils/fs.c index 549803a0..19c85814 100644 --- a/src/utils/fs.c +++ b/src/utils/fs.c @@ -70,6 +70,42 @@ bool file_allocate (char *path, size_t size) { return error; } +bool file_fill (char *path, uint8_t value) { + FIL fil; + bool error = false; + uint8_t buffer[FS_SECTOR_SIZE * 8]; + FRESULT res; + UINT bytes_to_write; + UINT bytes_written; + + for (int i = 0; i < sizeof(buffer); i++) { + buffer[i] = value; + } + + if (f_open(&fil, strip_sd_prefix(path), FA_WRITE) != FR_OK) { + return true; + } + + for (int i = 0; i < f_size(&fil); i += sizeof(buffer)) { + bytes_to_write = MIN(f_size(&fil) - f_tell(&fil), sizeof(buffer)); + res = f_write(&fil, buffer, bytes_to_write, &bytes_written); + if ((res != FR_OK) || (bytes_to_write != bytes_written)) { + error = true; + break; + } + } + + if (f_tell(&fil) != f_size(&fil)) { + error = true; + } + + if (f_close(&fil) != FR_OK) { + error = true; + } + + return error; +} + bool file_get_sectors (char *path, uint32_t *sectors, size_t entries) { FATFS *fs; FIL fil; diff --git a/src/utils/fs.h b/src/utils/fs.h index 2f70df12..25154437 100644 --- a/src/utils/fs.h +++ b/src/utils/fs.h @@ -16,6 +16,7 @@ bool file_exists (char *path); size_t file_get_size (char *path); bool file_delete (char *path); bool file_allocate (char *path, size_t size); +bool file_fill (char *path, uint8_t value); bool file_get_sectors (char *path, uint32_t *sectors, size_t entries); bool file_has_extensions (char *path, const char *extensions[]);