1 // Written by James Turner, started July 2010.
3 // Copyright (C) 2010 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
22 # include <simgear_config.h>
25 #include <simgear/misc/sg_dir.hxx>
26 #include <simgear/structure/exception.hxx>
32 # define WIN32_LEAN_AND_MEAN
37 # include <sys/types.h>
39 # include <sys/stat.h>
44 #include <simgear/debug/logstream.hxx>
45 #include <boost/foreach.hpp>
50 #include <algorithm> // for std::sort
58 _removeOnDestroy(false)
62 Dir::Dir(const SGPath& path) :
64 _removeOnDestroy(false)
66 _path.set_cached(false); // disable caching, so create/remove work
69 Dir::Dir(const Dir& rel, const SGPath& relPath) :
70 _path(rel.file(relPath.utf8Str())),
71 _removeOnDestroy(false)
73 _path.set_cached(false); // disable caching, so create/remove work
78 if (_removeOnDestroy) {
83 void Dir::setRemoveOnDestroy()
85 _removeOnDestroy = true;
92 char* buf = _getcwd(NULL, 0);
94 char *buf = ::getcwd(NULL, 0);
97 if (errno == 2) throw sg_exception("The current directory is invalid");
98 else throw sg_exception(strerror(errno));
106 Dir Dir::tempDir(const std::string& templ)
110 const char* tempPath = ::getenv("TMPDIR");
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
119 std::string s = p.local8BitStr();
120 ::snprintf(buf, 1024, "%s", s.c_str());
122 SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
126 return Dir(SGPath(buf));
128 SGPath p(tempnam(0, templ.c_str()));
130 if (!t.create(0700)) {
131 SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p);
138 static bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
140 return p1.file() < p2.file();
143 PathList Dir::children(int types, const std::string& nameFilter) const
147 types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
151 std::string search(_path.local8BitStr());
152 if (nameFilter.empty()) {
153 search += "\\*"; // everything
155 search += "\\*" + nameFilter;
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);
170 for (bool done = false; !done; done = (FindNextFile(find, &fData) == 0)) {
171 if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
172 if (!(types & INCLUDE_HIDDEN)) {
177 if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
178 if (types & NO_DOT_OR_DOTDOT) {
179 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
184 if (!(types & TYPE_DIR)) {
187 } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
188 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
190 continue; // always ignore device files
191 } else if (!(types & TYPE_FILE)) {
195 result.push_back(file(fData.cFileName));
200 std::string ps = _path.local8BitStr();
201 DIR* dp = opendir(ps.c_str());
203 SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path);
207 int filterLen = nameFilter.size();
210 struct dirent* entry = readdir(dp);
212 break; // done iteration
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, "..")) {
221 SGPath f = file(entry->d_name);
223 continue; // stat() failed
227 // directory handling
228 if (!(types & TYPE_DIR)) {
232 if (types & NO_DOT_OR_DOTDOT) {
233 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
237 } else if (f.isFile()) {
238 // regular file handling
239 if (!(types & TYPE_FILE)) {
243 // block device /fifo/char file, ignore
247 if (!nameFilter.empty()) {
248 int nameLen = strlen(entry->d_name);
249 if (nameLen < filterLen) {
250 continue; // name is shorter than the filter
253 char* nameSuffix = entry->d_name + (nameLen - filterLen);
254 if (strcmp(nameSuffix, nameFilter.c_str())) {
259 // passed all criteria, add to our result vector
260 result.push_back(file(entry->d_name));
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);
273 bool Dir::isEmpty() const
275 std::string ps = _path.local8BitStr();
277 return PathIsDirectoryEmpty( ps.c_str() );
279 DIR* dp = opendir( ps.c_str() );
280 if (!dp) return true;
284 while( (d = readdir(dp)) !=NULL && (n < 4) ) n++;
287 return (n == 2); // '.' and '..' always exist
291 bool Dir::exists() const
293 return _path.isDir();
296 SGPath Dir::file(const std::string& name) const
298 SGPath childPath = _path;
299 childPath.set_cached(true);
300 childPath.append(name);
305 # define sgMkDir(d,m) _mkdir(d)
307 # define sgMkDir(d,m) mkdir(d,m)
310 bool Dir::create(mode_t mode)
313 return false; // already exists
316 // recursively create parent directories
318 if (!pr.path().isNull() && !pr.exists()) {
319 bool ok = pr.create(mode);
325 // finally, create ourselves
326 std::string ps = _path.local8BitStr();
327 int err = sgMkDir(ps.c_str(), mode);
329 SG_LOG(SG_IO, SG_WARN, "directory creation failed: (" << _path << ") " << strerror(errno) );
335 bool Dir::removeChildren() const
338 PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
339 BOOST_FOREACH(SGPath path, cs) {
342 ok = childDir.remove(true);
348 SG_LOG(SG_IO, SG_WARN, "failed to remove:" << path);
351 } // of child iteration
356 bool Dir::remove(bool recursive)
359 SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path);
364 if (!removeChildren()) {
365 SG_LOG(SG_IO, SG_WARN, "Dir at:" << _path << " failed to remove children");
368 } // of recursive deletion
370 std::string ps = _path.local8BitStr();
372 int err = _rmdir(ps.c_str());
374 int err = rmdir(ps.c_str());
377 SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path << ":" << strerror(errno));
382 Dir Dir::parent() const
384 return Dir(_path.dir());
387 } // of namespace simgear