From 542001b14f7e6b9ba3ab5dcac329a454c1308b0f Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 9 May 2017 14:08:43 -0700 Subject: [PATCH] Update FileCache to use QSaveFile for atomic writes --- libraries/networking/src/FileCache.cpp | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/libraries/networking/src/FileCache.cpp b/libraries/networking/src/FileCache.cpp index 0ceda7a745..348206a863 100644 --- a/libraries/networking/src/FileCache.cpp +++ b/libraries/networking/src/FileCache.cpp @@ -17,6 +17,7 @@ #include #include +#include #include @@ -110,19 +111,13 @@ FilePointer FileCache::writeFile(const char* data, File::Metadata&& metadata) { return file; } - // write the data to a temporary file - std::string tmpFilepath = filepath + "_tmp"; - FILE* saveFile = fopen(tmpFilepath.c_str(), "wb"); - if (saveFile != nullptr && fwrite(data, metadata.length, 1, saveFile) && fclose(saveFile) == 0) { - int result = rename(tmpFilepath.c_str(), filepath.c_str()); - if (result == 0) { - file = addFile(std::move(metadata), filepath); - } else { - qCWarning(file_cache, "[%s] Failed to rename %s to %s (%s)", tmpFilepath.c_str(), filepath.c_str(), strerror(errno)); - } + QSaveFile saveFile(QString::fromStdString(filepath)); + saveFile.open(QIODevice::WriteOnly); + saveFile.write(data, metadata.length); + if (saveFile.commit()) { + file = addFile(std::move(metadata), filepath); } else { - qCWarning(file_cache, "[%s] Failed to write %s (%s)", _dirname.c_str(), metadata.key.c_str(), strerror(errno)); - errno = 0; + qCWarning(file_cache, "[%s] Failed to write %s", _dirname.c_str(), metadata.key.c_str()); } return file;