From 409a820589a0453197e0970e7048b82ad412c4c3 Mon Sep 17 00:00:00 2001 From: Jaakko Heinonen Date: Wed, 26 Oct 2005 16:38:35 +0000 Subject: [PATCH] - attempt to save database more safely - create a backup file when saving --- database.c | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/database.c b/database.c index 893cb99..bd88771 100644 --- a/database.c +++ b/database.c @@ -345,23 +345,41 @@ int save_database() { FILE *out; + int ret = 0; struct db_enumerator e = init_db_enumerator(ENUM_ALL); + char *datafile_new = strconcat(datafile, ".new", NULL); + char *datafile_old = strconcat(datafile, "~", NULL); - if( (out = abook_fopen(datafile, "w")) == NULL ) - return -1; + if( (out = abook_fopen(datafile_new, "w")) == NULL ) { + ret = -1; + goto out; + } if(list_is_empty()) { fclose(out); unlink(datafile); - return 1; + ret = 1; + goto out; } - + /* + * Possibly should check if write_database failed. + * Currently it returns always zero. + */ write_database(out, e); - fclose(out); - return 0; + if(access(datafile, F_OK) == 0 && + (rename(datafile, datafile_old)) == -1) + ret = -1; + + if((rename(datafile_new, datafile)) == -1) + ret = -1; + +out: + free(datafile_new); + free(datafile_old); + return ret; } static void -- 2.39.2