45 lines
1.2 KiB
C++
45 lines
1.2 KiB
C++
#include "PersistenceWriter.h"
|
|
|
|
#include <windows.h>
|
|
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
|
|
bool PersistenceWriter::WriteSnapshot(const PersistenceSnapshot& snapshot, std::string& error) const
|
|
{
|
|
if (snapshot.targetPath.empty())
|
|
{
|
|
error = "Persistence snapshot target path is empty.";
|
|
return false;
|
|
}
|
|
|
|
std::error_code fsError;
|
|
std::filesystem::create_directories(snapshot.targetPath.parent_path(), fsError);
|
|
|
|
const std::filesystem::path temporaryPath = snapshot.targetPath.string() + ".tmp";
|
|
std::ofstream output(temporaryPath, std::ios::binary | std::ios::trunc);
|
|
if (!output)
|
|
{
|
|
error = "Could not write file: " + temporaryPath.string();
|
|
return false;
|
|
}
|
|
|
|
output << snapshot.contents;
|
|
output.close();
|
|
if (!output.good())
|
|
{
|
|
error = "Could not finish writing file: " + temporaryPath.string();
|
|
return false;
|
|
}
|
|
|
|
if (!MoveFileExA(temporaryPath.string().c_str(), snapshot.targetPath.string().c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
|
|
{
|
|
const DWORD lastError = GetLastError();
|
|
std::filesystem::remove(temporaryPath, fsError);
|
|
error = "Could not replace file: " + snapshot.targetPath.string() + " (Win32 error " + std::to_string(lastError) + ")";
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|