1 #include "filesystem.hpp"
12 # include <sys/types.h>
21 using Stat = struct _stat;
22 int do_stat(const char *path, Stat &info) {
23 return _stat(path, &info);
25 bool is_dir(const Stat &info) {
26 return (info.st_mode & _S_IFDIR) != 0;
28 bool is_file(const Stat &info) {
29 return (info.st_mode & _S_IFEG) != 0;
32 using Stat = struct stat;
33 int do_stat(const char *path, Stat &info) {
34 return stat(path, &info);
36 bool is_dir(const Stat &info) {
37 return S_ISDIR(info.st_mode);
39 bool is_file(const Stat &info) {
40 return S_ISREG(info.st_mode);
43 std::time_t get_mtime(const Stat &info) {
45 return info.st_mtimespec.tv_sec;
52 bool is_dir(const char *path) {
54 if (do_stat(path, info) != 0) {
60 bool is_file(const char *path) {
62 if (do_stat(path, info) != 0) {
68 std::time_t file_mtime(const char *path) {
70 if (do_stat(path, info) != 0) {
73 return get_mtime(info);
77 bool make_dir(const char *path) {
79 int ret = _mkdir(path);
81 int ret = mkdir(path, 0777);
87 bool make_dirs(const std::string &path) {
98 auto pos = path.find_last_of("\\/");
100 auto pos = path.find_last_of('/');
102 if (pos == std::string::npos) {
105 if (pos == path.length() - 1) {
106 // trailing separator, would make final make_dir fail
108 pos = path.find_last_of("\\/", pos - 1);
110 pos = path.find_last_of('/', pos - 1);
112 if (pos == std::string::npos) {
116 if (!make_dirs(path.substr(0, pos))) {
121 return make_dir(path);
124 // something's there, check if it's a dir and we're good
128 // whatever else went wrong, it can't be good
135 bool remove_file(const std::string &path) {
136 return remove(path.c_str()) == 0;
140 bool remove_dir(const std::string &path) {
143 // shamelessly stolen from http://www.codeguru.com/forum/showthread.php?t=239271
144 const std::string pattern = path + "\\*.*";
145 WIN32_FIND_DATA info;
146 HANDLE file = FindFirstFile(pattern.c_str(), &info);
147 if (file == INVALID_HANDLE_VALUE) {
148 // already non-existing
154 strncmp(info.cFileName, ".", 2) == 0 ||
155 strncmp(info.cFileName, "..", 3) == 0
159 const std::string sub_path = path + '\\' + info.cFileName;
160 if ((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
161 if (!remove_dir(sub_path)) {
165 if (!SetFileAttributes(sub_path.c_str(), FILE_ATTRIBUTE_NORMAL)) {
168 if (!remove_file(sub_path)) {
172 } while (FindNextFile(file, &info));
175 DWORD error = GetLastError();
176 if (error != ERROR_NO_MORE_FILES) {
179 // is this (NORMAL vs DIRECTORY) really correct?
180 if (!SetFileAttributes(path.c_str(), FILE_ATTRIBUTE_NORMAL)) {
183 return RemoveDirectory(path.c_str());
187 DIR *dir = opendir(path.c_str());
188 for (dirent *entry = readdir(dir); entry != nullptr; entry = readdir(dir)) {
190 strncmp(entry->d_name, ".", 2) == 0 ||
191 strncmp(entry->d_name, "..", 3) == 0
195 const std::string sub_path = path + '/' + entry->d_name;
196 if (is_dir(sub_path)) {
197 if (!remove_dir(sub_path)) {
201 if (!remove_file(sub_path)) {
206 return remove(path.c_str()) == 0;