make a backup of save data before writing to it

This commit is contained in:
Alug 2025-04-18 12:52:24 +02:00 committed by NepDisk
parent ed7b667aa7
commit d8b6b8e981
3 changed files with 68 additions and 0 deletions

View file

@ -4635,6 +4635,7 @@ void G_SaveGameData(void)
INT32 i, j;
UINT8 btemp;
savebuffer_t save = {0};
char backupfile[MAX_WADPATH+4];
if (!gamedataloaded)
return; // If never loaded (-nodata), don't save
@ -4652,6 +4653,23 @@ void G_SaveGameData(void)
return;
}
// Create backup of the save data
snprintf(backupfile, sizeof(backupfile), "%s.bak", gamedatafilename);
backupfile[sizeof(backupfile) - 1] = '\0';
FILE *gamedata = fopen(gamedatafilename, "r");
if (gamedata != NULL)
{
fclose(gamedata);
if (!FIL_CopyFile(gamedatafilename, backupfile))
{
CONS_Alert(CONS_WARNING,"Failed to create a backup of save data. Will not attempt to write to save data\n");
return;
}
}
// Version test
WRITEUINT32(save.p, GD_VERSIONCHECK); // 4

View file

@ -363,6 +363,38 @@ boolean FIL_FileOK(char const *name)
return access(name,6)+1; //R_OK|W_OK
}
/** Copies contents of one file to another
*
* \param src File to copy from
* \param dst File to write into
* \return true if copy was succesful, false if it doesn't.
*/
boolean FIL_CopyFile(const char *src, const char *dst)
{
FILE *srcFile = fopen(src, "rb");
if (srcFile == NULL)
return false;
FILE *dstFile = fopen(dst, "wb");
if (dstFile == NULL)
{
fclose(srcFile);
return false;
}
char buffer[1024];
size_t n;
while ((n = fread(buffer, 1, sizeof(buffer), srcFile)) > 0)
fwrite(buffer, 1, n, dstFile);
fclose(srcFile);
fclose(dstFile);
return true;
}
/** Checks if a pathname has a file extension and adds the extension provided
* if not.
@ -573,11 +605,28 @@ void M_SaveConfig(const char *filename)
{
FILE *f;
char *filepath;
char backupfile[MAX_WADPATH+4];
// make sure not to write back the config until it's been correctly loaded
if (!gameconfig_loaded)
return;
// Create backup of the config file
snprintf(backupfile, sizeof backupfile, "%s.bak", configfile);
backupfile[sizeof backupfile - 1] = '\0';
FILE *config = fopen(configfile, "r");
if (config != NULL)
{
fclose(config);
if (FIL_CopyFile(configfile, backupfile) == false)
{
CONS_Alert(CONS_WARNING,"Failed to create a backup of the configuration file. Will not attempt to write to file\n");
return;
}
}
// can change the file name
if (filename)
{

View file

@ -56,6 +56,7 @@ boolean FIL_FileExists(const char *name);
boolean FIL_WriteFileOK(char const *name);
boolean FIL_ReadFileOK(char const *name);
boolean FIL_FileOK(char const *name);
boolean FIL_CopyFile(const char *src, const char *dst);
void FIL_DefaultExtension (char *path, const char *extension);
void FIL_ForceExtension(char *path, const char *extension);