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).
master
jp9000 2015-08-21 17:31:23 -07:00
parent be5283bb51
commit 3a77ac3516
2 changed files with 49 additions and 0 deletions

View File

@ -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;

View File

@ -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);