소스 검색

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).
jp9000 10 년 전
부모
커밋
3a77ac3516
2개의 변경된 파일49개의 추가작업 그리고 0개의 파일을 삭제
  1. 46 0
      libobs/util/platform.c
  2. 3 0
      libobs/util/platform.h

+ 46 - 0
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;

+ 3 - 0
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);