Skip to content

fix(SD): open(FILE_WRITE) must not truncate a file whose lookup failed - #94

Merged
fpistm merged 1 commit into
stm32duino:mainfrom
preobd:fix/open-no-truncate-on-read-error
Nov 20, 2026
Merged

fpistm merged 1 commit into
stm32duino:mainfrom
preobd:fix/open-no-truncate-on-read-error

Conversation

@preobd

@preobd preobd commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Fixes #93.

SDClass::open() called exists() to decide whether to add FA_CREATE_ALWAYS, and exists() returns false for any f_stat() error. A transient read error (FR_DISK_ERR) on the directory sector therefore made an existing file look absent, and f_open() then truncated it.

This uses FA_OPEN_ALWAYS for FILE_WRITE instead: the file is created if absent and opened untouched if present, and a read error makes the open fail instead of destroying data. It also drops one directory lookup per open. exists() itself is unchanged.

Tested on an Adafruit Feather STM32F405 (SDIO, 24 MHz, STM32SD 1.5.0, FatFs 4.0.4). disk_read was wrapped to fail the next sector read once, then SD.open(path, FILE_WRITE) was called on an existing file, 50 times per build:

stock this PR
injected read errors 50 50
existing file truncated 50 0
open() on error succeeds on a truncated file fails, file untouched
create when absent works works
append to existing works works

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 stm32duino#93
@fpistm fpistm added the fix 🩹 Bug fix label Nov 20, 2026
@fpistm fpistm added this to the 1.5.1/1.6.0 milestone Nov 20, 2026
@github-project-automation github-project-automation Bot moved this from In progress to Reviewer approved in STM32duino libraries Nov 20, 2026
@fpistm
fpistm merged commit 5774a25 into stm32duino:main Nov 20, 2026
12 checks passed
@github-project-automation github-project-automation Bot moved this from Reviewer approved to Done in STM32duino libraries Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix 🩹 Bug fix

Projects

Development

Successfully merging this pull request may close these issues.

SD.open(path, FILE_WRITE) truncates an existing file when exists() hits a read error

2 participants