Fix crashing bug -- can't append 1000s of times?

This commit is contained in:
Derek Jamison
2023-10-02 11:46:57 -05:00
parent 54c1f4fd13
commit 1044c0bf8c
5 changed files with 116 additions and 32 deletions

View File

@@ -27,47 +27,91 @@ static void ensure_save_folder_exists(Storage* storage) {
ensure_dir_exists(storage, GENIE_SAVE_FOLDER);
}
Storage* _storage;
File* _file;
void genie_file_init() {
_storage = furi_record_open(RECORD_STORAGE);
ensure_save_folder_exists(_storage);
_file = storage_file_alloc(_storage);
storage_file_open(
_file,
(GENIE_SAVE_FOLDER "/" GENIE_SAVE_NAME GENIE_SAVE_EXTENSION),
FSAM_WRITE,
FSOM_OPEN_APPEND);
}
void genie_file_close() {
if(_file) {
storage_file_close(_file);
_file = NULL;
}
if(_storage) {
furi_record_close(RECORD_STORAGE);
_storage = NULL;
}
}
void demo() {
Storage* storage = furi_record_open(RECORD_STORAGE);
File* file = storage_file_alloc(storage);
if(storage_file_open(
file,
(GENIE_SAVE_FOLDER "/" GENIE_SAVE_NAME GENIE_SAVE_EXTENSION),
FSAM_WRITE,
FSOM_OPEN_APPEND)) {
if(!storage_file_write(_file, "Hello\r\n", 7)) {
FURI_LOG_E(TAG, "Failed to write to file");
}
} else {
FURI_LOG_E(TAG, "Failed to open file");
}
storage_file_close(file);
furi_record_close(RECORD_STORAGE);
}
bool genie_save(uint32_t count, FuriString* key) {
bool success = false;
Storage* storage = furi_record_open(RECORD_STORAGE);
FuriString* file_path = furi_string_alloc();
// Storage* storage = furi_record_open(RECORD_STORAGE);
FuriString* buffer = furi_string_alloc();
furi_string_printf(buffer, "%08lX,%s\r\n", count, furi_string_get_cstr(key));
char buffer[8 + 1 + 16 + 2 + 1] = {0};
snprintf(buffer, 8 + 1 + 16 + 2 + 1, "%08lX,%s\r\n", count, furi_string_get_cstr(key));
furi_string_printf(
file_path, "%s/%s%s", GENIE_SAVE_FOLDER, GENIE_SAVE_NAME, GENIE_SAVE_EXTENSION);
File* file = NULL;
// File* file = NULL;
do {
if(!storage) {
FURI_LOG_E(TAG, "Failed to access storage");
break;
// if(!storage) {
// FURI_LOG_E(TAG, "Failed to access storage");
// break;
// }
// file = storage_file_alloc(storage);
// if(storage_file_open(
// file,
// (GENIE_SAVE_FOLDER "/" GENIE_SAVE_NAME GENIE_SAVE_EXTENSION),
// FSAM_WRITE,
// FSOM_OPEN_APPEND))
if(_file == NULL) {
genie_file_init();
}
ensure_save_folder_exists(storage);
file = storage_file_alloc(storage);
if(storage_file_open(file, furi_string_get_cstr(file_path), FSAM_WRITE, FSOM_OPEN_APPEND)) {
FURI_LOG_D(TAG, "Writing to file: %s", furi_string_get_cstr(file_path));
if(!storage_file_write(file, furi_string_get_cstr(buffer), furi_string_size(buffer))) {
if(_file) {
if(!storage_file_write(_file, buffer, COUNT_OF(buffer) - 1)) {
FURI_LOG_E(TAG, "Failed to write to file");
break;
}
storage_file_sync(_file);
success = true;
}
} while(false);
if(file) {
storage_file_close(file);
}
// if(file) {
// storage_file_close(file);
// }
furi_string_free(file_path);
furi_string_free(buffer);
furi_record_close(RECORD_STORAGE);
// furi_record_close(RECORD_STORAGE);
return success;
}