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