core/file: Refactor file opening code

Signed-off-by: Anna Schumaker <Anna@OcarinaProject.net>
This commit is contained in:
Anna Schumaker 2015-09-10 09:20:43 -04:00
parent 7e9eb9e7d2
commit a88da1dabf
2 changed files with 28 additions and 22 deletions

View File

@ -19,6 +19,11 @@ static const std::string find_ocarina_dir()
return res;
}
static bool __file_mkdir()
{
return g_mkdir_with_parents(find_ocarina_dir().c_str(), 0755) == 0;
}
file :: file(const std::string &name, unsigned int version)
: f_mode(NOT_OPEN), f_version(version), f_prev(0), f_name(name)
@ -53,32 +58,37 @@ bool file_exists(struct file *file)
return g_file_test(file_path(file).c_str(), G_FILE_TEST_EXISTS);
}
bool file :: _open_read()
static bool __file_open_common(struct file *file, OpenMode mode)
{
if (!file_exists(this))
((std::fstream *)file)->open(file_path(file).c_str(),
(mode == OPEN_READ) ? std::fstream::in : std::fstream::out);
if (file->fail())
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();
file->f_mode = mode;
return true;
}
bool file :: _open_write()
static bool __file_open_read(struct file *file)
{
if (g_mkdir_with_parents(find_ocarina_dir().c_str(), 0755) != 0)
if (!file_exists(file))
return false;
if (!__file_open_common(file, OPEN_READ))
return false;
std::fstream::open(file_path(this).c_str(), std::fstream::out);
if (std::fstream::fail())
*file >> file->f_prev;
file->getline();
return true;
}
static bool __file_open_write(struct file *file)
{
if (!__file_mkdir())
return false;
if (!__file_open_common(file, OPEN_WRITE))
return false;
f_mode = OPEN_WRITE;
std::fstream::operator<<(f_version) << std::endl;
*file << file->f_version << std::endl;
return true;
}
@ -87,10 +97,9 @@ 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();
if (mode == OPEN_READ)
return __file_open_read(this);
return __file_open_write(this);
}
void file :: close()

View File

@ -48,9 +48,6 @@ struct file : public std::fstream {
unsigned int f_prev; /* The file's on-disk data version. */
std::string f_name; /* The file's basename. */
bool _open_read();
bool _open_write();
/**
* Set up a new file object.
*