libobs/util: Add os_safe_replace function
Allows safely/atomically replacing a file and creating a backup of the original. The reason for adding this function is because Microsoft provides a ReplaceFile function which does this in a single call.
This commit is contained in:
@@ -557,6 +557,35 @@ error:
|
||||
return code;
|
||||
}
|
||||
|
||||
int os_safe_replace(const char *target, const char *from, const char *backup)
|
||||
{
|
||||
wchar_t *wtarget = NULL;
|
||||
wchar_t *wfrom = NULL;
|
||||
wchar_t *wbackup = NULL;
|
||||
int code = -1;
|
||||
|
||||
if (!target || !from)
|
||||
return -1;
|
||||
if (!os_utf8_to_wcs_ptr(target, 0, &wtarget))
|
||||
return -1;
|
||||
if (!os_utf8_to_wcs_ptr(from, 0, &wfrom))
|
||||
goto fail;
|
||||
if (backup && !os_utf8_to_wcs_ptr(backup, 0, &wbackup))
|
||||
goto fail;
|
||||
|
||||
if (ReplaceFileW(wtarget, wfrom, wbackup, 0, NULL, NULL)) {
|
||||
code = 0;
|
||||
} else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
|
||||
code = MoveFile(wfrom, wtarget) ? 0 : -1;
|
||||
}
|
||||
|
||||
fail:
|
||||
bfree(wtarget);
|
||||
bfree(wfrom);
|
||||
bfree(wbackup);
|
||||
return code;
|
||||
}
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE hinst_dll, DWORD reason, LPVOID reserved)
|
||||
{
|
||||
switch (reason) {
|
||||
|
Reference in New Issue
Block a user