ocarina/lib/file.cpp

145 lines
2.7 KiB
C++
Raw Normal View History

/*
* Copyright 2013 (c) Bryan Schumaker.
*/
#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
void File :: find_dir(std::string &res)
{
switch (hint) {
case FILE_TYPE_CONFIG:
res = g_get_user_config_dir();
break;
case FILE_TYPE_DATA:
res = g_get_user_data_dir();
break;
case FILE_TYPE_LEGACY:
res = g_get_home_dir();
}
res += "/";
switch (hint) {
case FILE_TYPE_CONFIG:
case FILE_TYPE_DATA:
res += OCARINA_DIR;
break;
case FILE_TYPE_LEGACY:
res += ".";
res += OCARINA_DIR;
}
}
File :: File(std::string path, FileLocHint file_hint)
: mode(NOT_OPEN), hint(file_hint)
{
std::string dir;
find_dir(dir);
filepath = 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);
}
bool File :: open_read()
{
if (!exists()) {
dprint("ERROR: File does not exist (%s)\n", filepath.c_str());
return false;
}
std::fstream::open(filepath.c_str(), std::fstream::in);
if (std::fstream::fail()) {
dprint("ERROR: Could not open file for reading (%s)\n", filepath.c_str());
return false;
}
mode = OPEN_READ;
std::fstream::operator>>(version);
getline();
return std::fstream::good();
}
bool File :: open_write()
{
std::string dir;
if (hint == FILE_TYPE_LEGACY) {
dprint("ERROR: Cannot write to legacy files (%s)\n", filepath.c_str());
return false;
}
find_dir(dir);
if (g_mkdir_with_parents(dir.c_str(), 0755) != 0) {
dprint("ERROR: Could not make directory (%s)\n", dir.c_str());
return false;
}
std::fstream::open(filepath.c_str(), std::fstream::out);
if (std::fstream::fail()) {
dprint("ERROR: Could not open file for writing (%s)\n", filepath.c_str());
return false;
}
mode = OPEN_WRITE;
std::fstream::operator<<(FILE_VERSION) << std::endl;
return std::fstream::good();
}
bool File :: open(OpenMode m)
{
if (mode != NOT_OPEN) {
dprint("ERROR: File is already open (%s)\n", filepath.c_str());
return false;
}
if (m == NOT_OPEN) {
dprint("ERROR: NOT_OPEN is not a legal OpenMode (%s)\n", filepath.c_str());
return false;
} else if (m == OPEN_READ)
return open_read();
else /* m == OPEN_WRITE */
return open_write();
}
bool File :: close()
{
if (mode != NOT_OPEN)
std::fstream::close();
mode = NOT_OPEN;
return std::fstream::good();
}
std::string File :: getline()
{
std::string res;
std::getline(*static_cast<std::fstream *>(this), res);
return res;
}