ocarina/core/file.cpp

116 lines
2.0 KiB
C++

/*
* Copyright 2013 (c) Anna Schumaker.
*/
#include <core/error.h>
#include <core/file.h>
#include <glib.h>
#ifdef CONFIG_TEST
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
File :: File(const std::string &name, unsigned int vers)
: mode(NOT_OPEN), filename(name), version(vers), prev_version(0)
{
}
File :: ~File()
{
close();
}
const std::string File :: find_dir()
{
std::string res(g_get_user_data_dir());
res += "/" + OCARINA_DIR;
return res;
}
const std::string File :: get_filepath()
{
std::string res = "";
if (filename != "") {
res = find_dir();
res += "/" + filename;
}
return res;
}
const unsigned int File :: get_version()
{
if (mode == OPEN_READ)
return prev_version;
return 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;
mode = OPEN_READ;
std::fstream::operator>>(prev_version);
getline();
return true;
}
bool File :: open_write()
{
if (g_mkdir_with_parents(find_dir().c_str(), 0755) != 0)
return false;
std::fstream::open(get_filepath().c_str(), std::fstream::out);
if (std::fstream::fail())
return false;
mode = OPEN_WRITE;
std::fstream::operator<<(version) << std::endl;
return true;
}
bool File :: open(OpenMode m)
{
if ((filename == "") || (m == NOT_OPEN) || (mode != NOT_OPEN))
return false;
else if (m == OPEN_READ)
return open_read();
else /* m == OPEN_WRITE */
return open_write();
}
void File :: close()
{
if (mode != NOT_OPEN)
std::fstream::close();
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;
}