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.
What you'll learn
- Explain at the
Linux kernelVFS syscall boundary whyQFile(QIODevice::WriteOnly | QIODevice::Truncate) corrupts live files on power loss whereasQSaveFilestays atomic. - Trace the
openat -> write -> fsync -> renamecommit path ofQSaveFile::commit()and the automaticunlinkrollback ofcancelWriting()and~QSaveFile(). - Serialize UTF-8
QTextStream(QStringConverter::Utf8) andQJsonDocument(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!
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().
- Step 1. Open QSaveFile at the target path so the temporary sibling resides on the same filesystem mount.
- Step 2. Serialize UTF-8 QJsonDocument or QTextStream content and abort via cancelWriting() on any short write.
- Step 3. Call QSaveFile::commit() (never close(), which is private) and check its boolean return status.
- 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()!
Figure 6.1b. Pairing Qt 6 I/O devices (QFile for reads, QSaveFile for writes) with UTF-8 serializers.
| Persistence Pattern | Kernel Syscall Sequence | 24 V Power-Cut Outcome | Recommended Role | |
|---|---|---|---|---|
| `QFile(WriteOnly | Truncate)` | openat(O_TRUNC) -> write -> close | 0-byte or half-written corrupt file! | NEVER use for critical config/calibration files |
| `QFile(WriteOnly | Append)` | openat(O_APPEND) -> write | Prior lines intact; tail line may truncate | Append-only diagnostic text logs with line CRCs |
QSaveFile + commit() | openat(.tmp) -> write -> fsync -> rename | Atomic: complete old file OR complete new file | All JSON/INI configs, recipes, and tare tables | |
QSaveFile without commit() | openat(.tmp) -> write -> close -> unlink | Clean rollback: .tmp removed, old file intact | Error recovery and exception-safe abort paths |
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; } };- QSaveFile::commit() flushes bytes to storage via fsync() and atomically swaps the directory entry via rename().
- Flush QTextStream and verify out.status() == QTextStream::Ok before committing UTF-8 text exports.
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 Host C++20 Verifier Traced Under strace for Atomic Commit and Unlink Rollback
In verify.cpp, we build a POSIX AtomicSaveTransaction matching QSaveFile's exact syscall sequence (openat sibling .tmp, write, fsync, close, rename, and destructor unlink rollback) and trace it live with strace -e trace=openat,write,fsync,rename,renameat,renameat2,unlink,exit_group!
Watch what happens across the two scopes in main(): scope 1 commits v1 (40 bytes) cleanly, while scope 2 writes a truncated corrupt string "{\"corrupt_half" and exits scope WITHOUT calling commit()—triggering destructor unlink so v1 survives byte-for-byte intact!
learner@ksa:~/gl-q01/m06-l01$ bat -H 48 -H 98 verify.cpp File: verify.cpp #include <cassert> #include <cstdio> #include <cstdlib> #include <fcntl.h> #include <string> #include <string_view> #include <unistd.h> class AtomicSaveTransaction { public: explicit AtomicSaveTransaction(std::string target) : m_target(std::move(target)), m_tmp(m_target + ".tmp") {} ~AtomicSaveTransaction() { if (m_active) cancel_writing(); } AtomicSaveTransaction(const AtomicSaveTransaction &) = delete; AtomicSaveTransaction &operator=(const AtomicSaveTransaction &) = delete; bool open_write() noexcept { m_fd = ::openat(AT_FDCWD, m_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); m_active = (m_fd >= 0); return m_active; } bool write_all(std::string_view bytes) noexcept { if (!m_active || m_fd < 0) return false; std::size_t off = 0; while (off < bytes.size()) { const ssize_t n = ::write(m_fd, bytes.data() + off, bytes.size() - off); if (n <= 0) { cancel_writing(); return false; } off += static_cast<std::size_t>(n); } return true; } void cancel_writing() noexcept { if (m_fd >= 0) { ::close(m_fd); m_fd = -1; } if (m_active) { ::unlink(m_tmp.c_str()); m_active = false; } } bool commit() noexcept { if (!m_active || m_fd < 0) return false; if (::fsync(m_fd) != 0) { cancel_writing(); return false; } ::close(m_fd); m_fd = -1; if (::rename(m_tmp.c_str(), m_target.c_str()) != 0) { ::unlink(m_tmp.c_str()); m_active = false; return false; } m_active = false; return true; } private: std::string m_target; std::string m_tmp; int m_fd = -1; bool m_active = false; }; static std::string read_file(const std::string &p) { const int fd = ::openat(AT_FDCWD, p.c_str(), O_RDONLY | O_CLOEXEC); assert(fd >= 0); char buf[256]{}; const ssize_t n = ::read(fd, buf, sizeof(buf) - 1U); ::close(fd); assert(n >= 0); return std::string(buf, static_cast<std::size_t>(n)); } int main() { char tpl[] = "./.qsave_verify_XXXXXX"; char *dir = ::mkdtemp(tpl); assert(dir != nullptr); const std::string cfg = std::string(dir) + "/calib.json"; const std::string v1 = R"({"schema_version":1,"zero":-15,"lim":420})"; { AtomicSaveTransaction tx(cfg); assert(tx.open_write()); assert(tx.write_all(v1)); assert(tx.commit()); } assert(read_file(cfg) == v1); { AtomicSaveTransaction aborted(cfg); assert(aborted.open_write()); assert(aborted.write_all(R"({"corrupt_half)")); // Leaves scope without commit() -> ~AtomicSaveTransaction() unlinks .tmp! } assert(::access((cfg + ".tmp").c_str(), F_OK) != 0); assert(read_file(cfg) == v1); ::unlink(cfg.c_str()); ::rmdir(dir); std::printf("savefile_audit: committed_bytes=%zu rollback_intact=1 tmp_cleaned=1\n", v1.size()); return 0; }- commit() flushes dirty pages via fsync(m_fd) BEFORE closing and executing atomic POSIX rename().
- Exiting scope without commit() triggers ~AtomicSaveTransaction() -> unlink(.tmp), keeping v1 intact.
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-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-l01learner@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
Key takeaways
- Opening an existing configuration file with
QFileandQIODevice::WriteOnly | QIODevice::Truncatezeroes the live inode immediately (O_TRUNC), leaving a0-byte or partial file if power fails mid-write. QSaveFilewrites to a sibling temporary file in the destination directory, flushes storage viafsync(), and atomically replaces the target via POSIXrename()insidecommit().- If
QSaveFileleaves scope without callingcommit()(or aftercancelWriting()),~QSaveFile()closes andunlink()s the temporary file while leaving the previous configuration file untouched. - Qt 6
QTextStreamdefaults toQStringConverter::Utf8(requiring explicitstatus() == QTextStream::Okchecks), whileQJsonDocument::fromJsonpinpoints syntax faults viaQJsonParseError.