From 71d81ad78b4f6e8326286360789b8d99108f8bec Mon Sep 17 00:00:00 2001 From: "chunmao.guo" Date: Fri, 26 Aug 2022 18:12:41 +0800 Subject: [PATCH] FIX: save backup mesh with temp file safely Change-Id: I39ed281e271add443c41cb177d203f0b0decf2b6 --- src/libslic3r/Format/bbs_3mf.cpp | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/libslic3r/Format/bbs_3mf.cpp b/src/libslic3r/Format/bbs_3mf.cpp index 789895a70..697a07730 100644 --- a/src/libslic3r/Format/bbs_3mf.cpp +++ b/src/libslic3r/Format/bbs_3mf.cpp @@ -3863,18 +3863,38 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) auto filename = boost::format("3D/Objects/%s_%d.model") % object.name % obj_id; std::string filepath = temp_path + "/" + filename.str(); - if (!open_zip_writer(&archive, filepath)) { + std::string filepath_tmp = filepath + ".tmp"; + boost::system::error_code ec; + boost::filesystem::remove(filepath_tmp, ec); + if (!open_zip_writer(&archive, filepath_tmp)) { add_error("Unable to open the file"); BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":" << __LINE__ << boost::format(", Unable to open the file\n"); return false; } + struct close_lock + { + mz_zip_archive & archive; + std::string const * filename; + void close() { + close_zip_writer(&archive); + filename = nullptr; + } + ~close_lock() { + if (filename) { + close_zip_writer(&archive); + boost::filesystem::remove(*filename); + } + } + } lock{archive, &filepath_tmp}; + IdToObjectDataMap objects_data; objects_data.insert({obj_id, {&object, obj_id}}); _add_model_file_to_archive(filename.str(), archive, model, objects_data); mz_zip_writer_finalize_archive(&archive); - close_zip_writer(&archive); + lock.close(); + boost::filesystem::rename(filepath_tmp, filepath, ec); return true; }