/* * Copyright 2013 (c) Anna Schumaker. */ #include #include #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 File :: File(const std::string &name) : mode(NOT_OPEN), filename(name), version(FILE_VERSION) { } File :: ~File() { close(); } const char *File :: find_dir() { std::string res = g_get_user_data_dir(); res += "/" + OCARINA_DIR; return res.c_str(); } const char *File :: get_filepath() { std::string res; if (filename != "") { res = find_dir(); res += "/" + filename; } return res.c_str(); } const unsigned int File :: get_version() { return version; } bool File :: exists() { return g_file_test(filename.c_str(), G_FILE_TEST_EXISTS); } bool File :: open_read() { if (!exists()) { dprint("ERROR: File does not exist\n"); return false; } std::fstream::open(get_filepath(), 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 (g_mkdir_with_parents(find_dir(), 0755) != 0) { dprint("ERROR: Could not make directory\n"); return false; } std::fstream::open(get_filepath(), 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 (filename == "") { dprint("ERROR: No filename specified\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(this), res); return res; }