From 021c055c08e9e682b2832d67a3e19b465cfeda6d Mon Sep 17 00:00:00 2001 From: preobd <123303208+preobd@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:05:57 -0500 Subject: [PATCH] fix(SD): open(FILE_WRITE) must not truncate a file whose lookup failed open() called exists() to decide whether to add FA_CREATE_ALWAYS, and exists() reports any f_stat() error as 'absent'. A transient read error (FR_DISK_ERR) on the directory sector therefore truncated an existing file. Use FA_OPEN_ALWAYS instead: create if absent, open untouched if present, and fail the open on a read error. Fixes #93 --- src/SD.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/SD.cpp b/src/SD.cpp index a5e99a9..eb6ddb0 100644 --- a/src/SD.cpp +++ b/src/SD.cpp @@ -150,8 +150,11 @@ File SDClass::open(const char *filepath, uint8_t mode /* = FA_READ */) file._dir.fs = 0; #endif - if ((mode == FILE_WRITE) && (!SD.exists(filepath))) { - mode = mode | FA_CREATE_ALWAYS; + if (mode == FILE_WRITE) { + /* Create the file if absent, open it untouched if present. Do not decide + * via exists(): a read error there would look like "absent" and + * FA_CREATE_ALWAYS would truncate an existing file. */ + mode = mode | FA_OPEN_ALWAYS; } file._res = f_open(file._fil, filepath, mode);