core/file: Add cache_file_close() function

Signed-off-by: Anna Schumaker <Anna@OcarinaProject.net>
This commit is contained in:
Anna Schumaker 2016-03-31 10:15:17 -04:00
parent e137eb0108
commit 9db9df619f
3 changed files with 28 additions and 17 deletions

View File

@ -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;

View File

@ -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.

View File

@ -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(