core/file: Rework binary file IO

I rename cache_file_write() to file_write(), and implement the
corresponding file_read() for binary data.

Signed-off-by: Anna Schumaker <Anna@NoWheyCreamery.com>
This commit is contained in:
Anna Schumaker 2018-02-20 16:44:57 -05:00
parent 07f832ad26
commit c5494811f4
4 changed files with 32 additions and 8 deletions

View File

@ -227,9 +227,26 @@ int data_file_writef(struct file *data, const char *fmt, ...)
return ret;
}
int cache_file_write(struct file *cache, const void *data, size_t len)
gchar *file_read(struct file *file)
{
if (fwrite(data, len, 1, cache->f_file) == 1)
int fd = fileno(file->f_file);
struct stat st;
gchar *buf;
if (fstat(fd, &st) < 0)
return NULL;
buf = g_malloc0(st.st_size + 1);
if (fread(buf, st.st_size, 1, file->f_file) == 1)
return buf;
g_free(buf);
return NULL;
}
int file_write(struct file *file, const void *data, size_t len)
{
if (fwrite(data, len, 1, file->f_file) == 1)
return len;
return -1;
}
@ -244,7 +261,7 @@ bool cache_file_import(struct file *cache, const gchar *srcpath)
if (!g_file_get_contents(srcpath, &contents, &length, NULL))
return false;
cache_file_write(cache, contents, length);
file_write(cache, contents, length);
return true;
}

View File

@ -65,8 +65,8 @@ static bool __album_fetch_cover(struct album *album, gchar *releaseid)
file = __album_alloc_file(album);
if (file_open(&file->ac_file, OPEN_WRITE_BINARY)) {
cache_file_write(&file->ac_file, caa_imagedata_data(image),
caa_imagedata_size(image));
file_write(&file->ac_file, caa_imagedata_data(image),
caa_imagedata_size(image));
file_close(&file->ac_file);
}
__album_free_file(file);

View File

@ -129,10 +129,16 @@ int data_file_readf(struct file *, const char *, ...);
int data_file_writef(struct file *, const char *, ...);
/*
* Write binary data to a cache file similar to fwrite(3).
* Reads the contents of a file as binary data.
* NOTE: This function returns a new string which MUST be freed with g_free().
*/
gchar *file_read(struct file *);
/*
* Write binary data a cache file, similar to fwrite(3).
* Returns the number of bytes successfully written.
*/
int cache_file_write(struct file *, const void *, size_t);
int file_write(struct file *, const void *, size_t);
/* Import a file into the cache. */
bool cache_file_import(struct file *, const gchar *);

View File

@ -202,7 +202,7 @@ static void test_cache()
g_assert_false(file_open(&file, OPEN_WRITE_BINARY));
g_assert_false(file_exists(&file));
g_assert_cmpuint(cache_file_write(&file, "abcde", 5), ==, 5);
g_assert_cmpuint(file_write(&file, "abcde", 5), ==, 5);
file_close(&file);
g_assert_null(file.f_file);
g_assert_cmpuint(file.f_mode, ==, CLOSED);
@ -212,6 +212,7 @@ static void test_cache()
g_assert_cmpuint(file.f_mode, ==, OPEN_READ_BINARY);
g_assert_cmpuint(file.f_version, ==, OCARINA_MINOR_VERSION);
g_assert_cmpuint(file.f_prev, ==, 0);
g_assert_cmpstr_free(file_read(&file), ==, "abcde");
file_close(&file);
/* Test importing a file into the cache. */