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