]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_dir.cxx
Fixed mingw build.
[simgear.git] / simgear / misc / sg_dir.cxx
1 // Written by James Turner, started July 2010.
2 //
3 // Copyright (C) 2010  Curtis L. Olson - http://www.flightgear.org/~curt
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // Library General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19 // $Id$
20
21 #ifdef HAVE_CONFIG_H
22 #  include <simgear_config.h>
23 #endif
24
25 #include <simgear/misc/sg_dir.hxx>
26 #include <math.h>
27 #include <stdlib.h>
28
29 #ifdef _WIN32
30 #  define WIN32_LEAN_AND_MEAN
31 #  include <windows.h>
32 #  include <direct.h>
33 #else
34 #  include <sys/types.h>
35 #  include <dirent.h>
36 #  include <sys/stat.h>
37 #  include <unistd.h>
38 #  include <errno.h>
39 #endif
40
41 #include <simgear/debug/logstream.hxx>
42 #include <boost/foreach.hpp>
43
44 #include <cstring>
45 #include <iostream>
46
47 using std::string;
48
49 namespace simgear
50 {
51
52 Dir::Dir() :
53     _removeOnDestroy(false)
54 {
55 }
56
57 Dir::Dir(const SGPath& path) :
58   _path(path),
59   _removeOnDestroy(false)
60 {
61     _path.set_cached(false); // disable caching, so create/remove work
62 }
63
64 Dir::Dir(const Dir& rel, const SGPath& relPath) :
65   _path(rel.file(relPath.str())),
66   _removeOnDestroy(false)
67 {
68     _path.set_cached(false); // disable caching, so create/remove work
69 }
70
71 Dir::~Dir()
72 {
73     if (_removeOnDestroy) {
74         remove(true);
75     }
76 }
77
78 void Dir::setRemoveOnDestroy()
79 {
80     _removeOnDestroy = true;
81 }
82
83 Dir Dir::current()
84 {
85 #ifdef _WIN32
86     char* buf = _getcwd(NULL, 0);
87 #else
88     char* buf = ::getcwd(NULL, 0);
89 #endif
90     SGPath p(buf);
91     free(buf);
92     return Dir(p);
93 }
94
95 Dir Dir::tempDir(const std::string& templ)
96 {
97 #ifdef HAVE_MKDTEMP
98     char buf[1024];
99     const char* tempPath = ::getenv("TMPDIR");
100     if (!tempPath) {
101         tempPath = "/tmp";
102     }
103     SGPath p(tempPath);
104     p.append(templ);
105     // Mac OS-X / BSD manual says any number of 'X's, but GLibc manual
106     // says exactly six, so that's what I'm going with
107     p.concat("-XXXXXX");
108     ::snprintf(buf, 1024, "%s", p.c_str());
109     if (!mkdtemp(buf)) {
110         SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
111         return Dir();
112     }
113     
114     return Dir(SGPath(buf));
115 #else
116     SGPath p(tempnam(0, templ.c_str()));
117     Dir t(p);
118     if (!t.create(0700)) {
119         SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p.str());
120     }
121     
122     return t;
123 #endif
124 }
125
126 PathList Dir::children(int types, const std::string& nameFilter) const
127 {
128   PathList result;
129   if (types == 0) {
130     types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
131   }
132   
133 #ifdef _WIN32
134   std::string search(_path.str());
135   if (nameFilter.empty()) {
136     search += "\\*"; // everything
137   } else {
138     search += "\\*" + nameFilter;
139   }
140   
141   WIN32_FIND_DATA fData;
142   HANDLE find = FindFirstFile(search.c_str(), &fData);
143   if (find == INVALID_HANDLE_VALUE) {
144     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: FindFirstFile failed:" << _path.str());
145     return result;
146   }
147   
148   bool done = false;
149   for (bool done = false; !done; done = (FindNextFile(find, &fData) == 0)) {
150     if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
151       if (!(types & INCLUDE_HIDDEN)) {
152         continue;
153       }
154     }
155     
156     if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
157           if (types & NO_DOT_OR_DOTDOT) {
158                 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
159                   continue;
160                 }
161           }
162
163       if (!(types & TYPE_DIR)) {
164         continue;
165       }
166         } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
167                                 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
168         {
169                 continue; // always ignore device files
170     } else if (!(types & TYPE_FILE)) {
171        continue;
172     }
173
174     result.push_back(file(fData.cFileName));
175   }
176
177   FindClose(find);
178 #else
179   DIR* dp = opendir(_path.c_str());
180   if (!dp) {
181     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path.str());
182     return result;
183   }
184   
185   int filterLen = nameFilter.size();
186   
187   while (true) {
188     struct dirent* entry = readdir(dp);
189     if (!entry) {
190       break; // done iteration
191     }
192     
193     // skip hidden files (names beginning with '.') unless requested
194     if (!(types & INCLUDE_HIDDEN) && (entry->d_name[0] == '.') &&
195          strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
196       continue;
197     }
198     
199     SGPath f = file(entry->d_name);
200     if (!f.exists()) {
201       continue; // stat() failed
202     }
203     
204     if (f.isDir()) {
205       // directory handling
206       if (!(types & TYPE_DIR)) {
207         continue;
208       }
209       
210       if (types & NO_DOT_OR_DOTDOT) {
211         if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
212           continue;
213         }
214       }
215     } else if (f.isFile()) {
216       // regular file handling
217       if (!(types & TYPE_FILE)) {
218         continue;
219       }
220     } else {
221       // block device /fifo/char file, ignore
222       continue;
223     }
224
225     if (!nameFilter.empty()) {
226       int nameLen = strlen(entry->d_name);
227       if (nameLen < filterLen) {
228         continue; // name is shorter than the filter
229       }
230     
231       char* nameSuffix = entry->d_name + (nameLen - filterLen);
232       if (strcmp(nameSuffix, nameFilter.c_str())) {
233         continue;
234       }
235     }
236     
237   // passed all criteria, add to our result vector
238     result.push_back(file(entry->d_name));
239   }
240   
241   closedir(dp);
242 #endif
243   return result;
244 }
245
246 bool Dir::exists() const
247 {
248   return _path.isDir();
249 }
250
251 SGPath Dir::file(const std::string& name) const
252 {
253   SGPath childPath = _path;
254   childPath.set_cached(true);
255   childPath.append(name);
256   return childPath;  
257 }
258
259 #ifdef _WIN32
260 #  define sgMkDir(d,m)       _mkdir(d)
261 #else
262 #  define sgMkDir(d,m)       mkdir(d,m)
263 #endif
264
265 bool Dir::create(mode_t mode)
266 {
267     if (exists()) {
268         return false; // already exists
269     }
270     
271 // recursively create parent directories
272     Dir pr(parent());
273     if (!pr.path().isNull() && !pr.exists()) {
274         bool ok = pr.create(mode);
275         if (!ok) {
276             return false;
277         }
278     }
279     
280 // finally, create ourselves
281     int err = sgMkDir(_path.c_str(), mode);
282     if (err) {
283         SG_LOG(SG_IO, SG_WARN,  "directory creation failed: (" << _path.str() << ") " << strerror(errno) );
284     }
285     
286     return (err == 0);
287 }
288
289 bool Dir::remove(bool recursive)
290 {
291     if (!exists()) {
292         SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path.str());
293         return false;
294     }
295     
296     if (recursive) {
297         bool ok;
298         PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
299         BOOST_FOREACH(SGPath path, cs) {
300             if (path.isDir()) {
301                 Dir childDir(path);
302                 ok = childDir.remove(true);
303             } else {
304                 ok = path.remove();
305             }
306             
307             if (!ok) {
308                 return false;
309             }
310         } // of child iteration
311     } // of recursive deletion
312     
313 #ifdef _WIN32
314     int err = _rmdir(_path.c_str());
315 #else
316     int err = rmdir(_path.c_str());
317 #endif
318     if (err) {
319         SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path.str() << ":" << strerror(errno));
320     }
321     return (err == 0);
322 }
323
324 Dir Dir::parent() const
325 {
326     return Dir(_path.dir());
327 }
328
329 } // of namespace simgear