]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_dir.cxx
Fix Dir warnings on Windows.
[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 #include <cstdio>
29
30 #ifdef _WIN32
31 #  define WIN32_LEAN_AND_MEAN
32 #  include <windows.h>
33 #  include <direct.h>
34 #else
35 #  include <sys/types.h>
36 #  include <dirent.h>
37 #  include <sys/stat.h>
38 #  include <unistd.h>
39 #  include <errno.h>
40 #endif
41
42 #include <simgear/debug/logstream.hxx>
43 #include <boost/foreach.hpp>
44
45 #include <cstring>
46 #include <cstdlib>
47 #include <iostream>
48 #include <algorithm> // for std::sort
49
50 using std::string;
51
52 namespace simgear
53 {
54
55 Dir::Dir() :
56     _removeOnDestroy(false)
57 {
58 }
59
60 Dir::Dir(const SGPath& path) :
61   _path(path),
62   _removeOnDestroy(false)
63 {
64     _path.set_cached(false); // disable caching, so create/remove work
65 }
66
67 Dir::Dir(const Dir& rel, const SGPath& relPath) :
68   _path(rel.file(relPath.str())),
69   _removeOnDestroy(false)
70 {
71     _path.set_cached(false); // disable caching, so create/remove work
72 }
73
74 Dir::~Dir()
75 {
76     if (_removeOnDestroy) {
77         remove(true);
78     }
79 }
80
81 void Dir::setRemoveOnDestroy()
82 {
83     _removeOnDestroy = true;
84 }
85
86 Dir Dir::current()
87 {
88 #ifdef _WIN32
89     char* buf = _getcwd(NULL, 0);
90 #else
91     char* buf = ::getcwd(NULL, 0);
92 #endif
93     SGPath p(buf);
94     free(buf);
95     return Dir(p);
96 }
97
98 Dir Dir::tempDir(const std::string& templ)
99 {
100 #ifdef HAVE_MKDTEMP
101     char buf[1024];
102     const char* tempPath = ::getenv("TMPDIR");
103     if (!tempPath) {
104         tempPath = "/tmp";
105     }
106     SGPath p(tempPath);
107     p.append(templ);
108     // Mac OS-X / BSD manual says any number of 'X's, but GLibc manual
109     // says exactly six, so that's what I'm going with
110     p.concat("-XXXXXX");
111     ::snprintf(buf, 1024, "%s", p.c_str());
112     if (!mkdtemp(buf)) {
113         SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
114         return Dir();
115     }
116     
117     return Dir(SGPath(buf));
118 #else
119     SGPath p(tempnam(0, templ.c_str()));
120     Dir t(p);
121     if (!t.create(0700)) {
122         SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p.str());
123     }
124     
125     return t;
126 #endif
127 }
128
129 static bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
130 {
131   return p1.file() < p2.file();
132 }
133
134 PathList Dir::children(int types, const std::string& nameFilter) const
135 {
136   PathList result;
137   if (types == 0) {
138     types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
139   }
140   
141 #ifdef _WIN32
142   std::string search(_path.str());
143   if (nameFilter.empty()) {
144     search += "\\*"; // everything
145   } else {
146     search += "\\*" + nameFilter;
147   }
148   
149   WIN32_FIND_DATA fData;
150   HANDLE find = FindFirstFile(search.c_str(), &fData);
151   if (find == INVALID_HANDLE_VALUE) {
152           int err = GetLastError();
153           if (err != ERROR_FILE_NOT_FOUND) {
154                 SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: FindFirstFile failed:" << 
155                         _path.str() << " with error:" << err);
156           }
157     return result;
158   }
159   
160   bool done = false;
161   for (bool done = false; !done; done = (FindNextFile(find, &fData) == 0)) {
162     if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
163       if (!(types & INCLUDE_HIDDEN)) {
164         continue;
165       }
166     }
167     
168     if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
169           if (types & NO_DOT_OR_DOTDOT) {
170                 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
171                   continue;
172                 }
173           }
174
175       if (!(types & TYPE_DIR)) {
176         continue;
177       }
178         } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
179                                 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
180         {
181                 continue; // always ignore device files
182     } else if (!(types & TYPE_FILE)) {
183        continue;
184     }
185
186     result.push_back(file(fData.cFileName));
187   }
188
189   FindClose(find);
190 #else
191   DIR* dp = opendir(_path.c_str());
192   if (!dp) {
193     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path.str());
194     return result;
195   }
196   
197   int filterLen = nameFilter.size();
198   
199   while (true) {
200     struct dirent* entry = readdir(dp);
201     if (!entry) {
202       break; // done iteration
203     }
204     
205     // skip hidden files (names beginning with '.') unless requested
206     if (!(types & INCLUDE_HIDDEN) && (entry->d_name[0] == '.') &&
207          strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
208       continue;
209     }
210     
211     SGPath f = file(entry->d_name);
212     if (!f.exists()) {
213       continue; // stat() failed
214     }
215     
216     if (f.isDir()) {
217       // directory handling
218       if (!(types & TYPE_DIR)) {
219         continue;
220       }
221       
222       if (types & NO_DOT_OR_DOTDOT) {
223         if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
224           continue;
225         }
226       }
227     } else if (f.isFile()) {
228       // regular file handling
229       if (!(types & TYPE_FILE)) {
230         continue;
231       }
232     } else {
233       // block device /fifo/char file, ignore
234       continue;
235     }
236
237     if (!nameFilter.empty()) {
238       int nameLen = strlen(entry->d_name);
239       if (nameLen < filterLen) {
240         continue; // name is shorter than the filter
241       }
242     
243       char* nameSuffix = entry->d_name + (nameLen - filterLen);
244       if (strcmp(nameSuffix, nameFilter.c_str())) {
245         continue;
246       }
247     }
248     
249   // passed all criteria, add to our result vector
250     result.push_back(file(entry->d_name));
251   }
252   
253   closedir(dp);
254 #endif
255
256   // File system order is random. Make things deterministic,
257   // so it's the same for every user.
258   std::sort(result.begin(), result.end(), pathSortPredicate);
259
260   return result;
261 }
262
263 bool Dir::isEmpty() const
264 {
265   bool empty= true;
266 #ifdef _WIN32 
267   WIN32_FIND_DATA fData;
268   HANDLE find = FindFirstFile("\\*", &fData);
269   if (find == INVALID_HANDLE_VALUE) {
270     return true;
271   }
272   
273 // since an empty dir will still have . and .. children, we need
274 // watch for those - anything else means the dir is really non-empty
275   bool done = false;
276   for (; !done; done = (FindNextFile(find, &fData) == 0)) {
277     if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
278                   if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
279                     continue;
280                   }
281           }
282     
283     empty = false;
284     break;
285   }
286     
287   FindClose(find);
288 #else
289   DIR* dp = opendir(_path.c_str());
290   if (!dp) {
291     return true;
292   }
293     
294   while (true) {
295     struct dirent* entry = readdir(dp);
296     if (!entry) {
297       break; // done iteration
298     }
299     
300     if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
301       continue;
302     }
303       
304     empty = false;
305     break;
306   }
307   closedir(dp);
308 #endif
309   return empty;
310 }
311
312 bool Dir::exists() const
313 {
314   return _path.isDir();
315 }
316
317 SGPath Dir::file(const std::string& name) const
318 {
319   SGPath childPath = _path;
320   childPath.set_cached(true);
321   childPath.append(name);
322   return childPath;  
323 }
324
325 #ifdef _WIN32
326 #  define sgMkDir(d,m)       _mkdir(d)
327 #else
328 #  define sgMkDir(d,m)       mkdir(d,m)
329 #endif
330
331 bool Dir::create(mode_t mode)
332 {
333     if (exists()) {
334         return false; // already exists
335     }
336     
337 // recursively create parent directories
338     Dir pr(parent());
339     if (!pr.path().isNull() && !pr.exists()) {
340         bool ok = pr.create(mode);
341         if (!ok) {
342             return false;
343         }
344     }
345     
346 // finally, create ourselves
347     int err = sgMkDir(_path.c_str(), mode);
348     if (err) {
349         SG_LOG(SG_IO, SG_WARN,  "directory creation failed: (" << _path.str() << ") " << strerror(errno) );
350     }
351     
352     return (err == 0);
353 }
354
355 bool Dir::removeChildren() const
356 {
357     bool ok;
358     PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
359     BOOST_FOREACH(SGPath path, cs) {
360         if (path.isDir()) {
361             Dir childDir(path);
362             ok = childDir.remove(true);
363         } else {
364             ok = path.remove();
365         }
366         
367         if (!ok) {
368             SG_LOG(SG_IO, SG_WARN, "failed to remove:" << path);
369             return false;
370         }
371     } // of child iteration
372     
373     return true;
374 }
375
376 bool Dir::remove(bool recursive)
377 {
378     if (!exists()) {
379         SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path);
380         return false;
381     }
382     
383     if (recursive) {
384         if (!removeChildren()) {
385             return false;
386         }
387     } // of recursive deletion
388     
389 #ifdef _WIN32
390     int err = _rmdir(_path.c_str());
391 #else
392     int err = rmdir(_path.c_str());
393 #endif
394     if (err) {
395         SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path.str() << ":" << strerror(errno));
396     }
397     return (err == 0);
398 }
399
400 Dir Dir::parent() const
401 {
402     return Dir(_path.dir());
403 }
404
405 } // of namespace simgear