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