QFile, QTextStream & Crash-Atomic QSaveFile Configuration Persistence

Eliminate zero-byte configuration corruption on sudden 24 V power loss by replacing QFile QIODevice::Truncate overwrites with QSaveFile sibling temp writes, fsync, and atomic rename.

30 minfree previewLinux 6.12→ module 6 lab
What you'll learn
  • Explain at the Linux kernel VFS syscall boundary why QFile (QIODevice::WriteOnly | QIODevice::Truncate) corrupts live files on power loss whereas QSaveFile stays atomic.
  • Trace the openat -> write -> fsync -> rename commit path of QSaveFile::commit() and the automatic unlink rollback of cancelWriting() and ~QSaveFile().
  • Serialize UTF-8 QTextStream (QStringConverter::Utf8) and QJsonDocument (QJsonParseError) payloads with all-or-nothing schema validation.

Why Truncate-in-Place Destroys Embedded Configurations on Power Loss

Field technicians shut down industrial machinery by throwing the main 24 V cabinet disconnect without clicking an OS shutdown menu. When an HMI saves calibration constants via QFile f("calib.json"); f.open(QIODevice::WriteOnly);, Qt passes O_WRONLY | O_CREAT | O_TRUNC to openat() in the Linux kernel. That O_TRUNC flag zeroes the existing file's length to 0 bytes BEFORE your first write() executes!

If power drops two milliseconds later—or if ext4 delayed allocation has not yet flushed dirty page-cache blocks to eMMC flash—the machine reboots to a 0-byte or half-written calib.json and loses its factory sensor tare offsets.

QSaveFile eliminates that window completely. open(QIODevice::WriteOnly) opens a hidden sibling temporary file in the same directory as calib.json (guaranteeing the same filesystem mount so rename() never fails with EXDEV). If an error or early return occurs before commit(), ~QSaveFile() automatically calls cancelWriting() and unlink()s the temporary file, leaving the prior calib.json 100% intact!

fig_m06_l01_a.svg — Linux kernel VFS syscall comparison between in-place…

Figure 6.1a. Linux kernel VFS syscall comparison between in-place QFile truncation and transactional .

mental model: Overwriting calibration constants with QFile(WriteOnly | Truncate) is like wiping your shop's only reference whiteboard clean before copying new tolerances from a notebook; QSaveFile writes and verifies a second board first, then hangs it over the wall hooks in a single atomic swap.

Where it stops working: Hanging a physical board is immediately permanent, whereas POSIX rename() only updates the directory dentry atomically—the temporary file's data blocks MUST be flushed via fsync() before rename(), and newly created files also benefit from syncing the parent directory descriptor on ext4.

definition (QSaveFile Atomic Persistence Transaction): QSaveFile subclasses QFileDevice (deliberately hiding close() as private) to enforce transactional POSIX file replacement. open(QIODevice::WriteOnly) creates a sibling .XXXXXX temporary file on the same mounted filesystem (preventing EXDEV cross-device rename errors), commit() executes fsync() + atomic rename(), and cancelWriting() aborts cleanly via unlink().

ast_m06_l01.svg — Ban QFile::Truncate on configs; write UTF-8 into…step 1/4
  1. Step 1. Open QSaveFile at the target path so the temporary sibling resides on the same filesystem mount.
  2. Step 2. Serialize UTF-8 QJsonDocument or QTextStream content and abort via cancelWriting() on any short write.
  3. Step 3. Call QSaveFile::commit() (never close(), which is private) and check its boolean return status.
  4. Step 4. Parse with QFile(ReadOnly) + QJsonParseError and validate domain limits before applying settings.

Figure 6.1b. Ban QFile::Truncate on configs; write UTF-8 into QSaveFile, check errors, and commit().

QSaveFile::commit Internals, UTF-8 QTextStream, and QJsonDocument Validation

Notice a deliberate compile-time safeguard in QSaveFile: QSaveFile::close() is declared private! If migrating QFile code accidentally calls file.close(), compilation fails immediately so you cannot silently bypass commit(). Calling file.commit() flushes user-space buffers, invokes fsync() on the temporary file descriptor so NAND blocks settle on flash, closes the descriptor, and executes atomic POSIX rename() over the destination filename.

Pair QSaveFile with clean UTF-8 serializers. For structured machine configs, build a QJsonObject with an explicit schema "version" integer and serialize via QJsonDocument(obj).toJson(QJsonDocument::Compact). On startup, read via QFile(QIODevice::ReadOnly), pass &QJsonParseError to QJsonDocument::fromJson, and range-check every parameter into local variables before mutating live controller state.

For human-readable audit exports (CSV or INI), attach QTextStream stream(&saveFile). In Qt 6, QTextStream defaults to QStringConverter::Utf8 out of the box—just remember to call stream.flush() and verify stream.status() == QTextStream::Ok before calling saveFile.commit()!

fig_m06_l01_b.svg — Pairing Qt 6 I/O devices (QFile for reads, QSaveFile…

Figure 6.1b. Pairing Qt 6 I/O devices (QFile for reads, QSaveFile for writes) with UTF-8 serializers.

Persistence PatternKernel Syscall Sequence24 V Power-Cut OutcomeRecommended Role
`QFile(WriteOnlyTruncate)`openat(O_TRUNC) -> write -> close0-byte or half-written corrupt file!NEVER use for critical config/calibration files
`QFile(WriteOnlyAppend)`openat(O_APPEND) -> writePrior lines intact; tail line may truncateAppend-only diagnostic text logs with line CRCs
QSaveFile + commit()openat(.tmp) -> write -> fsync -> renameAtomic: complete old file OR complete new fileAll JSON/INI configs, recipes, and tare tables
QSaveFile without commit()openat(.tmp) -> write -> close -> unlinkClean rollback: .tmp removed, old file intactError recovery and exception-safe abort paths
learner@ksa: ~/gl-q01/m06-l01
learner@ksa:~/gl-q01/m06-l01$ bat -H 33 -H 45 atomic_config_persistence.cpp File: atomic_config_persistence.cpp    #include <QFile>    #include <QJsonDocument>    #include <QJsonObject>    #include <QJsonParseError>    #include <QSaveFile>    #include <QString>    #include <QStringConverter>    #include <QTextStream>        struct CalibrationConfig {        int zeroOffsetKpa = 0;        int alarmLimitKpa = 420;    };        class CalibrationPersistence {    public:        static bool saveJsonAtomic(const QString &path, const CalibrationConfig &cfg) {            if (cfg.alarmLimitKpa <= 0 || cfg.alarmLimitKpa > 1000) return false;                QSaveFile file(path); // Opens sibling temp file in same directory            if (!file.open(QIODevice::WriteOnly)) return false;                QJsonObject root;            root[QStringLiteral("schema_version")] = 1;            root[QStringLiteral("zero_offset_kpa")] = cfg.zeroOffsetKpa;            root[QStringLiteral("alarm_limit_kpa")] = cfg.alarmLimitKpa;                const QByteArray utf8 = QJsonDocument(root).toJson(QJsonDocument::Compact);            if (file.write(utf8) != utf8.size()) {                file.cancelWriting(); // Explicit rollback (also run by ~QSaveFile)                return false;            }          return file.commit(); // fsync(tmp_fd) + atomic POSIX rename()!        }            static bool exportCsvAuditAtomic(const QString &path, const CalibrationConfig &cfg) {            QSaveFile file(path);            if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false;                QTextStream out(&file);            out.setEncoding(QStringConverter::Utf8);            out << "parameter,value_kpa    "                << "zero_offset," << cfg.zeroOffsetKpa << '  '                << "alarm_limit," << cfg.alarmLimitKpa << '    ';            out.flush();            if (out.status() != QTextStream::Ok) {                file.cancelWriting();                return false;            }            return file.commit();        }            static bool loadJsonValidated(const QString &path, CalibrationConfig &out) {            QFile file(path);            if (!file.open(QIODevice::ReadOnly)) return false;                QJsonParseError err{};            const QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &err);            if (err.error != QJsonParseError::NoError || !doc.isObject()) return false;                const QJsonObject obj = doc.object();            const int limit = obj.value(QStringLiteral("alarm_limit_kpa")).toInt(-1);            if (limit <= 0 || limit > 1000) return false;                out.zeroOffsetKpa = obj.value(QStringLiteral("zero_offset_kpa")).toInt(0);            out.alarmLimitKpa = limit;            return true;        }    };
  1. QSaveFile::commit() flushes bytes to storage via fsync() and atomically swaps the directory entry via rename().
  2. Flush QTextStream and verify out.status() == QTextStream::Ok before committing UTF-8 text exports.
QSaveFile-QTextStream(3qt) at a glance — GL-Q01
QSaveFile-QTextStream(3qt)  GL-Q01 Quick Reference  QSaveFile-QTextStream(3qt) NAME       QSaveFile, QFile, QTextStream, QJsonDocument - crash-atomic Qt 6       configuration persistence SYNOPSIS       QSaveFile sf(targetPath);       if (!sf.open(QIODevice::WriteOnly)) return false;       if (sf.write(payload) != payload.size()) { sf.cancelWriting(); return false; }       return sf.commit();                     // close() is intentionally private!        DURABILITY & ROLLBACK INVARIANTS 1. Never open existing config files       with QFile(QIODevice::WriteOnly | QIODevice::Truncate). 2. Sibling temp       file stays in targetPath's directory so rename(2) never fails with       EXDEV. 3. Destroying QSaveFile without commit() automatically unlinks       the temporary file. Kernel Systems Academy          Lesson 6.1          QSaveFile-QTextStream(3qt) GL-Q01 quick reference · full manual page: man 3qt QSaveFile-QTextStream 

Inspecting the Live Kernel strace Transcript of Commit and Rollback

Examine the strace capture below line by line! Transaction 1 executes openat(".../calib.json.tmp") -> write(...) -> fsync(...) -> rename(".../calib.json.tmp", ".../calib.json"), proving the live path was never truncated in place.

Immediately below it, Transaction 2 opens calib.json.tmp, writes "{\"corrupt_half", and calls unlink(".../calib.json.tmp") on scope exit—leaving calib.json untouched on disk.

learner@ksa: ~/gl-q01/m06-l01
learner@ksa:~/gl-q01/m06-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m06-l01./verifysavefile_audit: committed_bytes=41 rollback_intact=1 tmp_cleaned=1learner@ksa:~/gl-q01/m06-l01
strace — learner@ksa: ~/gl-q01/m06-l01
learner@ksa:~/gl-q01/m06-l01strace -e \trace=openat,write,fsync,rename,renameat,renameat2,unlink,exit_group ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libstdc++.so.6", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libgcc_s.so.1", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libm.so.6", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json.tmp", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "{\"schema_version\":1,\"zero\":-15,\""..., 41) = 41fsync(3)                                = 0rename("./.qsave_verify_KmSvV3/calib.json.tmp", "./.qsave_verify_KmSvV3/calib.json") = 0openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json.tmp", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "{\"corrupt_half", 14)         = 14unlink("./.qsave_verify_KmSvV3/calib.json.tmp") = 0openat(AT_FDCWD, "./.qsave_verify_KmSvV3/calib.json", O_RDONLY|O_CLOEXEC) = 3unlink("./.qsave_verify_KmSvV3/calib.json") = 0write(1, "savefile_audit: committed_bytes="..., 67) = 67exit_group(0)                           = ?+++ exited with 0 +++

Filesystem Mount Boundaries, Missing QTextStream Flushes, and Flash Wear

QSaveFile turns fragile configuration writes into crash-atomic transactions with five lines of C++20. Next, Lesson 6.2 moves from flash persistence to 60 Hz visual rendering: custom QPainter gauges, premultiplied ARGB32 Porter-Duff math, and real-time QtCharts batching.

Note the target storage boundary: fsync() durability depends on the underlying eMMC controller honoring CACHE FLUSH (EXT_CSD cache control) on Linux kernel 6.12.

Staging Temporary Config Files in /tmp Before Calling rename() to /etc or /var:

  • Symptom: Custom atomic-save helper works in desktop unit tests where everything is one root partition, then fails with EXDEV (Invalid cross-device link) on the embedded target.
  • Root Cause: Embedded rootfs layouts mount /tmp as a RAM-backed tmpfs, and POSIX rename() cannot move inodes across distinct filesystem mounts.
  • Fix: Use QSaveFile(targetPath), which always creates its temporary file in the exact same directory as targetPath.

Calling QSaveFile::commit() at 50 Hz on Every Slider Drag Step:

  • Symptom: Dragging a calibration slider stutters the GUI thread for tens of milliseconds per tick and accelerates eMMC NAND wear.
  • Root Cause: Each QSaveFile::commit() executes a synchronous blocking fsync() barrier down to flash storage.
  • Fix: Update RAM state live at 60 Hz, and trigger QSaveFile::commit() only on explicit 'Apply', dialog accept, or a debounced single-shot timer.

Guided Practice

Extend AtomicSaveTransaction::commit() in verify.cpp to also openat(AT_FDCWD, parent_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC) and fsync(dir_fd) right after rename(). Re-run under strace and observe the second fsync ensuring the directory entry itself is durable on freshly formatted ext4 partitions.

Independent Practice

Write a C++20 configuration loader with automatic .bak fallback that verifies a trailing CRC32 field inside the JSON object and rejects files whose schema version exceeds the running firmware's supported version.

Verification Checks

quiz · 1 of 3

A function opens QSaveFile sf("/var/lib/hmi/calib.json"), writes half a JSON object, and returns early on an error without calling sf.commit(). What is left on disk?

quiz · 2 of 3

Why does QSaveFile create its temporary file in the same directory as the destination path instead of /tmp?

quiz · 3 of 3

Why does calling sf.close() on a QSaveFile instance fail to compile in Qt 6?

Key takeaways

  • Opening an existing configuration file with QFile and QIODevice::WriteOnly | QIODevice::Truncate zeroes the live inode immediately (O_TRUNC), leaving a 0-byte or partial file if power fails mid-write.
  • QSaveFile writes to a sibling temporary file in the destination directory, flushes storage via fsync(), and atomically replaces the target via POSIX rename() inside commit().
  • If QSaveFile leaves scope without calling commit() (or after cancelWriting()), ~QSaveFile() closes and unlink()s the temporary file while leaving the previous configuration file untouched.
  • Qt 6 QTextStream defaults to QStringConverter::Utf8 (requiring explicit status() == QTextStream::Ok checks), while QJsonDocument::fromJson pinpoints syntax faults via QJsonParseError.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure