ocarina/lib/file.cpp

149 lines
2.7 KiB
C++

/*
* Copyright 2013 (c) Anna Schumaker.
*/
#include <error.h>
#include <file.h>
#include <print.h>
#include <glib.h>
#ifdef CONFIG_TEST
#define OCARINA_DIR "ocarina-test"
#elif CONFIG_DEBUG
#define OCARINA_DIR "ocarina-debug"
#else
#define OCARINA_DIR "ocarina"
#endif
File :: File(const std::string &path, FileLocHint file_hint)
: mode(NOT_OPEN), hint(file_hint), version(FILE_VERSION)
{
if (path.size() == 0)
hint = FILE_TYPE_INVALID;
if (hint == FILE_TYPE_INVALID)
filepath = "INVALID";
else
filepath = find_dir() + "/" + path;
}
File :: ~File()
{
close();
}
const char *File :: get_filepath()
{
return filepath.c_str();
}
const unsigned int File :: get_version()
{
return version;
}
bool File :: exists()
{
return g_file_test(filepath.c_str(), G_FILE_TEST_EXISTS);
}
std::string File :: find_dir()
{
std::string res;
if (hint == FILE_TYPE_DATA) {
res = g_get_user_data_dir();
res += "/";
res += OCARINA_DIR;
} else /* FILE_TYPE_LEGACY */ {
res = g_get_home_dir();
res += "/.";
res += OCARINA_DIR;
res += "/library";
}
return res;
}
bool File :: open_read()
{
if (!exists()) {
dprint("ERROR: File does not exist\n");
return false;
}
std::fstream::open(filepath.c_str(), std::fstream::in);
if (std::fstream::fail()) {
dprint("ERROR: File could not be opened for reading\n");
return false;
}
mode = OPEN_READ;
std::fstream::operator>>(version);
getline();
return true;
}
bool File :: open_write()
{
if (hint == FILE_TYPE_LEGACY) {
dprint("ERROR: Cannot write to legacy files\n");
return false;
}
std::string dir = find_dir();
if (g_mkdir_with_parents(dir.c_str(), 0755) != 0) {
dprint("ERROR: Could not make directory\n");
return false;
}
std::fstream::open(filepath.c_str(), std::fstream::out);
if (std::fstream::fail()) {
dprint("ERROR: Could not open file for writing\n");
return false;
}
mode = OPEN_WRITE;
std::fstream::operator<<(FILE_VERSION) << std::endl;
return true;
}
bool File :: open(OpenMode m)
{
if (hint == FILE_TYPE_INVALID) {
dprint("ERROR: A file with hint = FILE_TYPE_INVALID cannot be opened\n");
return false;
} else if (m == NOT_OPEN) {
dprint("ERROR: NOT_OPEN is not a legal OpenMode\n");
return false;
} else if (mode != NOT_OPEN) {
dprint("ERROR: File is already open\n");
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;
}