/** * Copyright 2013 (c) Anna Schumaker. */ #include #include #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 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) : _mode(NOT_OPEN), _filename(name), _version(version), _prev_version(0) { } File :: ~File() { close(); } const std::string File :: get_filepath() { std::string res = ""; if (_filename != "") { res = find_ocarina_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_ocarina_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 mode) { if ((_filename == "") || (mode == NOT_OPEN) || (_mode != NOT_OPEN)) return false; else if (mode == OPEN_READ) return _open_read(); else /* mode == 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(this), res); return res; }