diff --git a/targets/ESP32/_common/targetHAL_StorageOperation.cpp b/targets/ESP32/_common/targetHAL_StorageOperation.cpp index 6de75ba283..c7739198d6 100644 --- a/targets/ESP32/_common/targetHAL_StorageOperation.cpp +++ b/targets/ESP32/_common/targetHAL_StorageOperation.cpp @@ -32,32 +32,37 @@ uint32_t HAL_StorageOperation( size_t result; StorageOperationErrorCode errorCode = StorageOperationErrorCode::NoError; - + EnsureStorageInitialized(); + // check if the name is not empty + if (nameLength == 0) + { + return StorageOperationErrorCode::WriteError; + } + // convert storageName to char* char *strName = (char *)platform_malloc(nameLength + 1); - + // sanity check for successfull malloc if (strName == NULL) { return StorageOperationErrorCode::PlatformError; } - for (uint32_t i = 0; i < nameLength; i++) - { - strName[i] = static_cast(data[i]); - } + // go and copy the name + memcpy(strName, data, nameLength); // Just making sure it's properly 0 terminated strName[nameLength] = '\0'; + // !! the returned char* needs to be freed !! char *storageNameChar = ConvertToVfsPath(strName); // Cleaning the temporary name buffer platform_free(strName); - if (operation == (uint8_t)(StorageOperation_Monitor::StorageOperation_Write)) + if (operation == StorageOperation_Monitor::StorageOperation_Write) { // Remove the file if already exists remove(storageNameChar); @@ -69,34 +74,40 @@ uint32_t HAL_StorageOperation( result = fwrite((const void *)(data + nameLength), 1, (size_t)dataLength, file); fclose(file); + // check if the data was written if (result != (size_t)dataLength) { errorCode = StorageOperationErrorCode::WriteError; } } - else if (operation == (uint8_t)(StorageOperation_Monitor::StorageOperation_Append)) + else if (operation == StorageOperation_Monitor::StorageOperation_Append) { // Open the file in read mode FILE *file = fopen(storageNameChar, "a"); fseek(file, 0, SEEK_END); + // append more data result = fwrite((const void *)(data + nameLength), 1, (size_t)dataLength, file); fclose(file); + // check if the data was written if (result != (size_t)dataLength) { errorCode = StorageOperationErrorCode::WriteError; } } - else if (operation == (uint8_t)(StorageOperation_Monitor::StorageOperation_Delete)) + else if (operation == StorageOperation_Monitor::StorageOperation_Delete) { result = remove(storageNameChar); + + // check if the file was deleted if (result != 0) { errorCode = StorageOperationErrorCode::DeleteError; } } + // free buffer memory if (storageNameChar != NULL) { platform_free(storageNameChar);