ocarina/core/file.cpp

115 lines
2.1 KiB
C++
Raw Normal View History

/**
* Copyright 2013 (c) Anna Schumaker.
*/
#include <core/file.h>
#include <glib.h>
#ifdef CONFIG_TESTING
const std::string OCARINA_DIR = "ocarina-test";
#elif CONFIG_DEBUG
const std::string OCARINA_DIR = "ocarina-debug";
#else
const std::string OCARINA_DIR = "ocarina";
#endif
static const std::string find_ocarina_dir()
{
std::string res(g_get_user_data_dir());
res += "/" + OCARINA_DIR;
return res;
}
file :: file(const std::string &name, unsigned int version)
: f_mode(NOT_OPEN), f_version(version), f_prev(0), f_name(name)
{
}
file :: ~file()
{
close();
}
const std::string file_path(struct file *file)
{
std::string res = "";
if (file->f_name != "") {
res = find_ocarina_dir();
res += "/" + file->f_name;
}
return res;
}
const unsigned int file_version(struct file *file)
{
if (file->f_mode == OPEN_READ)
return file->f_prev;
return file->f_version;
}
bool file_exists(struct file *file)
{
return g_file_test(file_path(file).c_str(), G_FILE_TEST_EXISTS);
}
bool file :: _open_read()
{
if (!file_exists(this))
return false;
std::fstream::open(file_path(this).c_str(), std::fstream::in);
if (std::fstream::fail())
return false;
f_mode = OPEN_READ;
std::fstream::operator>>(f_prev);
getline();
return true;
}
bool file :: _open_write()
{
if (g_mkdir_with_parents(find_ocarina_dir().c_str(), 0755) != 0)
return false;
std::fstream::open(file_path(this).c_str(), std::fstream::out);
if (std::fstream::fail())
return false;
f_mode = OPEN_WRITE;
std::fstream::operator<<(f_version) << std::endl;
return true;
}
bool file :: open(OpenMode mode)
{
if ((f_name == "") || (mode == NOT_OPEN) || (f_mode != NOT_OPEN))
return false;
else if (mode == OPEN_READ)
return _open_read();
else /* mode == OPEN_WRITE */
return _open_write();
}
void file :: close()
{
if (f_mode != NOT_OPEN)
std::fstream::close();
f_mode = NOT_OPEN;
}
std::string file :: getline()
{
char c;
std::string res;
/* Ignore leading whitespace */
while (peek() == ' ')
read(&c, 1);
std::getline(*static_cast<std::fstream *>(this), res);
return res;
}