From: Ingo Ruhnke Date: Mon, 18 Aug 2014 09:33:04 +0000 (+0200) Subject: Added FileSystem::exists(), FileSystem::is_directory() and FileSystem::mkdir() X-Git-Url: https://git.verplant.org/?a=commitdiff_plain;h=a97a839d6e0dad2acfa327ae320bba41183cdd55;p=supertux.git Added FileSystem::exists(), FileSystem::is_directory() and FileSystem::mkdir() --- diff --git a/src/util/file_system.cpp b/src/util/file_system.cpp index 524d4a530..5b2ee00b5 100644 --- a/src/util/file_system.cpp +++ b/src/util/file_system.cpp @@ -17,10 +17,65 @@ #include "util/log.hpp" #include +#include +#include +#include #include +#ifdef _WIN32 +# include +#else +# include +#endif + namespace FileSystem { +bool exists(const std::string& path) +{ +#ifdef _WIN32 + DWORD dwAttrib = GetFileAttributes(path.c_str()); + + return (dwAttrib != INVALID_FILE_ATTRIBUTES && + !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); +#else + return !access(path.c_str(), F_OK); +#endif +} + +bool is_directory(const std::string& path) +{ + struct stat info; + + if (stat(path.c_str(), &info ) != 0) + { + // access error + return false; + } + else if (info.st_mode & S_IFDIR) + { + return true; + } + else + { + return false; + } +} + +void mkdir(const std::string& directory) +{ +#ifdef _WIN32 + if (!CreateDirectory(directory.c_str())) + { + throw std::runtime_error("failed to create directory: " + directory); + } +#else + if (::mkdir(directory.c_str(), 0777) != 0) + { + throw std::runtime_error("failed to create directory: " + directory); + } +#endif +} + std::string dirname(const std::string& filename) { std::string::size_type p = filename.find_last_of('/'); diff --git a/src/util/file_system.hpp b/src/util/file_system.hpp index 0e9783504..ff300026b 100644 --- a/src/util/file_system.hpp +++ b/src/util/file_system.hpp @@ -19,6 +19,17 @@ namespace FileSystem { +/** Returns true if the given path is a directory */ +bool is_directory(const std::string& path); + +/** Return true if the given file exists */ +bool exists(const std::string& path); + +/** + * Create the given directory + */ +void mkdir(const std::string& directory); + /** * returns the path of the directory the file is in */