Refactor file loading functions: simplify LoadFile, add LoadConfigFile, and adjust platform handling

This commit is contained in:
scawful
2024-12-29 10:44:22 -05:00
parent 1b7b56d7dc
commit bf862f2d5a
2 changed files with 37 additions and 13 deletions

View File

@@ -29,8 +29,31 @@ std::string GetFileName(const std::string &filename) {
return filename.substr(slash + 1);
}
std::string LoadFile(const std::string &filename, Platform platform) {
std::string LoadFile(const std::string &filename) {
std::string contents;
std::ifstream file(filename);
if (file.is_open()) {
std::stringstream buffer;
buffer << file.rdbuf();
contents = buffer.str();
file.close();
} else {
// Throw an exception
throw std::runtime_error("Could not open file: " + filename);
}
return contents;
}
std::string LoadConfigFile(const std::string &filename) {
std::string contents;
Platform platform;
#if defined(_WIN32)
platform = Platform::kWindows;
#elif defined(__APPLE__)
platform = Platform::kMacOS;
#else
platform = Platform::kLinux;
#endif
std::string filepath = GetConfigDirectory(platform) + "/" + filename;
std::ifstream file(filepath);
if (file.is_open()) {
@@ -55,18 +78,18 @@ void SaveFile(const std::string &filename, const std::string &contents,
std::string GetConfigDirectory(Platform platform) {
std::string config_directory = ".yaze";
switch (platform) {
case Platform::kWindows:
config_directory = "~/AppData/Roaming/yaze";
break;
case Platform::kMacOS:
case Platform::kLinux:
config_directory = "~/.config/yaze";
break;
default:
break;
case Platform::kWindows:
config_directory = "~/AppData/Roaming/yaze";
break;
case Platform::kMacOS:
case Platform::kLinux:
config_directory = "~/.config/yaze";
break;
default:
break;
}
return config_directory;
}
} // namespace core
} // namespace yaze
} // namespace core
} // namespace yaze

View File

@@ -10,7 +10,8 @@ enum class Platform { kUnknown, kMacOS, kiOS, kWindows, kLinux };
std::string GetFileExtension(const std::string &filename);
std::string GetFileName(const std::string &filename);
std::string LoadFile(const std::string &filename, Platform platform);
std::string LoadFile(const std::string &filename);
std::string LoadConfigFile(const std::string &filename);
std::string GetConfigDirectory(Platform platform);
void SaveFile(const std::string &filename, const std::string &data,