/* * Copyright 2013 (c) Bryan Schumaker. */ #include #include #include #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), version(FILE_VERSION) { std::string dir; find_dir(dir); filepath = dir + "/" + path; } File :: ~File() { close(); } const char *File :: get_filepath() { return filepath.c_str(); } 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; } stream.open(filepath.c_str(), std::fstream::in); if (stream.fail()) { dprint("ERROR: Could not open file for reading (%s)\n", filepath.c_str()); return false; } mode = OPEN_READ; stream >> version; return stream.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; } stream.open(filepath.c_str(), std::fstream::out); if (stream.fail()) { dprint("ERROR: Could not open file for writing (%s)\n", filepath.c_str()); return false; } mode = OPEN_WRITE; stream << version << std::endl; return stream.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) stream.close(); mode = NOT_OPEN; return stream.good(); }