]> git.localhorst.tv Git - blank.git/blob - src/app/io.cpp
(hopefully) cross-platform directory functions
[blank.git] / src / app / io.cpp
1 #include "io.hpp"
2
3 #include <cerrno>
4 #ifdef _WIN32
5 #  include <direct.h>
6 #endif
7 #include <sys/stat.h>
8
9
10 namespace blank {
11
12 bool is_dir(const char *path) {
13 #ifdef _WIN32
14         struct _stat info;
15         if (_stat(path, &info) != 0) {
16                 return false;
17         }
18         return (info.st_mode & _S_IFDIR) != 0;
19 #else
20         struct stat info;
21         if (stat(path, &info) != 0) {
22                 return false;
23         }
24         return (info.st_mode & S_IFDIR) != 0;
25 #endif
26 }
27
28
29 bool make_dir(const char *path) {
30 #ifdef _WIN32
31         int ret = _mkdir(path);
32 #else
33         int ret = mkdir(path, 0777);
34 #endif
35         return ret == 0;
36 }
37
38
39 bool make_dirs(const std::string &path) {
40         if (make_dir(path.c_str())) {
41                 return true;
42         }
43
44         switch (errno) {
45
46                 case ENOENT:
47                         // missing component
48                         {
49 #ifdef _WIN32
50                                 auto pos = path.find_last_of("\\/");
51 #else
52                                 auto pos = path.find_last_of('/');
53 #endif
54                                 if (pos == std::string::npos) {
55                                         return false;
56                                 }
57                                 if (!make_dirs(path.substr(0, pos))) {
58                                         return false;
59                                 }
60                         }
61                         // try again
62                         return make_dir(path.c_str());
63
64                 case EEXIST:
65                         // something's there, check if it's a dir and we're good
66                         return is_dir(path.c_str());
67
68                 default:
69                         // whatever else went wrong, it can't be good
70                         return false;
71
72         }
73 }
74
75 }