From 9db9df619f8c81a8ed6ccae244d98ad94053e6b1 Mon Sep 17 00:00:00 2001 From: Anna Schumaker Date: Thu, 31 Mar 2016 10:15:17 -0400 Subject: [PATCH] core/file: Add cache_file_close() function Signed-off-by: Anna Schumaker --- core/file.c | 39 +++++++++++++++++++++++---------------- include/core/file.h | 3 ++- tests/core/file.c | 3 +++ 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/core/file.c b/core/file.c index e65ec686..8978c0e5 100644 --- a/core/file.c +++ b/core/file.c @@ -57,6 +57,18 @@ static FILE *__file_open(gchar *path, const gchar *mode) return ret; } +static void __file_close(FILE *file, gchar *path, gchar *tmp) +{ + if (file) { + fclose(file); + if (path && tmp) + g_rename(tmp, path); + } + + g_free(path); + g_free(tmp); +} + static bool __file_mkdir(const gchar *basedir, const gchar *subdir) { gchar *dir = __file_path(basedir, subdir, NULL); @@ -80,17 +92,6 @@ static bool __file_can_write(struct file *file) return ret; } -static void __file_rename_tmp(struct file *file) -{ - gchar *path = file_path(file); - gchar *real = file_write_path(file); - - g_rename(real, path); - - g_free(real); - g_free(path); -} - void file_init(struct file *file, const gchar *name, unsigned int version, unsigned int min) @@ -209,14 +210,20 @@ bool cache_file_open(struct cache_file *file, enum open_mode mode) void file_close(struct file *file) { - if (file->f_file) { - fclose(file->f_file); - if (file->f_mode == OPEN_WRITE) - __file_rename_tmp(file); - } + __file_close(file->f_file, + file->f_mode == OPEN_WRITE ? file_path(file) : NULL, + file->f_mode == OPEN_WRITE ? file_write_path(file) : NULL); file->f_file = NULL; } +void cache_file_close(struct cache_file *file) +{ + __file_close(file->cf_file, + cache_file_path(file), + cache_file_write_path(file)); + file->cf_file = NULL; +} + int file_readf(struct file *file, const char *fmt, ...) { va_list argp; diff --git a/include/core/file.h b/include/core/file.h index 86663848..ad10d297 100644 --- a/include/core/file.h +++ b/include/core/file.h @@ -111,10 +111,11 @@ bool file_open(struct file *, enum open_mode); bool cache_file_open(struct cache_file *, enum open_mode); /* - * Closes an open file, setting file->f_file to NULL. If the file was opened + * Closes an open file, setting file->{f|cf}_file to NULL. If the file was opened * with OPEN_WRITE, then rename the temporary file to file_path(). */ void file_close(struct file *); +void cache_file_close(struct cache_file *); /* * Read an entire line from the file and return it to the caller. diff --git a/tests/core/file.c b/tests/core/file.c index 0c5743b9..6d172f78 100644 --- a/tests/core/file.c +++ b/tests/core/file.c @@ -166,6 +166,9 @@ static void test_cache() test_equal(cache_file_open(&file, OPEN_WRITE), (bool)false); test_equal(cache_file_exists(&file), (bool)false); + cache_file_close(&file); + test_equal((void *)file.cf_file, NULL); + test_equal(cache_file_exists(&file), (bool)true); } DECLARE_UNIT_TESTS(