From 3a77ac3516c6bac28f83224f4c019ce4965bb078 Mon Sep 17 00:00:00 2001 From: jp9000 Date: Fri, 21 Aug 2015 17:31:23 -0700 Subject: [PATCH] libobs/util: Add os_quick_write_utf8_file_safe This helper function saves to a temporary file first, (optionally) backs up the original file, then renames the temporary file to the actual file name. This helps reduce the chance of file corruption under various circumstances (such as shutdown or crash while the file is being written to disk). --- libobs/util/platform.c | 46 ++++++++++++++++++++++++++++++++++++++++++ libobs/util/platform.h | 3 +++ 2 files changed, 49 insertions(+) diff --git a/libobs/util/platform.c b/libobs/util/platform.c index 0b07cac6b..2496b9938 100644 --- a/libobs/util/platform.c +++ b/libobs/util/platform.c @@ -236,6 +236,52 @@ bool os_quick_write_utf8_file(const char *path, const char *str, size_t len, return true; } +bool os_quick_write_utf8_file_safe(const char *path, const char *str, + size_t len, bool marker, const char *temp_ext, + const char *backup_ext) +{ + struct dstr backup_path = {0}; + struct dstr temp_path = {0}; + bool success = false; + + if (!temp_ext || !*temp_ext) { + blog(LOG_ERROR, "os_quick_write_utf8_file_safe: invalid " + "temporary extension specified"); + return false; + } + + dstr_copy(&temp_path, path); + if (*temp_ext != '.') + dstr_cat(&temp_path, "."); + dstr_cat(&temp_path, temp_ext); + + if (!os_quick_write_utf8_file(temp_path.array, str, len, marker)) { + goto cleanup; + } + + if (backup_ext && *backup_ext) { + dstr_copy(&backup_path, path); + if (*backup_ext != '.') + dstr_cat(&backup_path, "."); + dstr_cat(&backup_path, backup_ext); + + os_unlink(backup_path.array); + os_rename(path, backup_path.array); + + dstr_free(&backup_path); + } else { + os_unlink(path); + } + + os_rename(temp_path.array, path); + success = true; + +cleanup: + dstr_free(&backup_path); + dstr_free(&temp_path); + return success; +} + size_t os_mbs_to_wcs(const char *str, size_t len, wchar_t *dst, size_t dst_size) { size_t out_len; diff --git a/libobs/util/platform.h b/libobs/util/platform.h index 33982aec7..8d0013cda 100644 --- a/libobs/util/platform.h +++ b/libobs/util/platform.h @@ -44,6 +44,9 @@ EXPORT size_t os_fread_utf8(FILE *file, char **pstr); EXPORT char *os_quick_read_utf8_file(const char *path); EXPORT bool os_quick_write_utf8_file(const char *path, const char *str, size_t len, bool marker); +EXPORT bool os_quick_write_utf8_file_safe(const char *path, const char *str, + size_t len, bool marker, const char *temp_ext, + const char *backup_ext); EXPORT char *os_quick_read_mbs_file(const char *path); EXPORT bool os_quick_write_mbs_file(const char *path, const char *str, size_t len);