diff --git a/src/g_game.c b/src/g_game.c index 5fa83f9d9..09001f2a6 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -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 diff --git a/src/m_misc.cpp b/src/m_misc.cpp index 7f0672d84..840d6213b 100644 --- a/src/m_misc.cpp +++ b/src/m_misc.cpp @@ -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) { diff --git a/src/m_misc.h b/src/m_misc.h index d739c0f57..3f5b97e4e 100644 --- a/src/m_misc.h +++ b/src/m_misc.h @@ -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);