115 lines
2.0 KiB
C++
115 lines
2.0 KiB
C++
/**
|
|
* 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 :: get_filepath()
|
|
{
|
|
std::string res = "";
|
|
|
|
if (f_name != "") {
|
|
res = find_ocarina_dir();
|
|
res += "/" + f_name;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
const unsigned int file :: get_version()
|
|
{
|
|
if (f_mode == OPEN_READ)
|
|
return f_prev;
|
|
return f_version;
|
|
}
|
|
|
|
bool file :: exists()
|
|
{
|
|
return g_file_test(get_filepath().c_str(), G_FILE_TEST_EXISTS);
|
|
}
|
|
|
|
bool file :: _open_read()
|
|
{
|
|
if (!exists())
|
|
return false;
|
|
|
|
std::fstream::open(get_filepath().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(get_filepath().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;
|
|
}
|