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>
31 # define WIN32_LEAN_AND_MEAN
35 # include <sys/types.h>
37 # include <sys/stat.h>
42 #include <simgear/debug/logstream.hxx>
43 #include <boost/foreach.hpp>
48 #include <algorithm> // for std::sort
56 _removeOnDestroy(false)
60 Dir::Dir(const SGPath& path) :
62 _removeOnDestroy(false)
64 _path.set_cached(false); // disable caching, so create/remove work
67 Dir::Dir(const Dir& rel, const SGPath& relPath) :
68 _path(rel.file(relPath.str())),
69 _removeOnDestroy(false)
71 _path.set_cached(false); // disable caching, so create/remove work
76 if (_removeOnDestroy) {
81 void Dir::setRemoveOnDestroy()
83 _removeOnDestroy = true;
89 char* buf = _getcwd(NULL, 0);
91 char* buf = ::getcwd(NULL, 0);
98 Dir Dir::tempDir(const std::string& templ)
102 const char* tempPath = ::getenv("TMPDIR");
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
111 ::snprintf(buf, 1024, "%s", p.c_str());
113 SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
117 return Dir(SGPath(buf));
119 SGPath p(tempnam(0, templ.c_str()));
121 if (!t.create(0700)) {
122 SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p.str());
129 static bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
131 return p1.file() < p2.file();
134 PathList Dir::children(int types, const std::string& nameFilter) const
138 types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
142 std::string search(_path.str());
143 if (nameFilter.empty()) {
144 search += "\\*"; // everything
146 search += "\\*" + nameFilter;
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);
161 for (bool done = false; !done; done = (FindNextFile(find, &fData) == 0)) {
162 if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
163 if (!(types & INCLUDE_HIDDEN)) {
168 if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
169 if (types & NO_DOT_OR_DOTDOT) {
170 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
175 if (!(types & TYPE_DIR)) {
178 } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
179 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
181 continue; // always ignore device files
182 } else if (!(types & TYPE_FILE)) {
186 result.push_back(file(fData.cFileName));
191 DIR* dp = opendir(_path.c_str());
193 SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path.str());
197 int filterLen = nameFilter.size();
200 struct dirent* entry = readdir(dp);
202 break; // done iteration
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, "..")) {
211 SGPath f = file(entry->d_name);
213 continue; // stat() failed
217 // directory handling
218 if (!(types & TYPE_DIR)) {
222 if (types & NO_DOT_OR_DOTDOT) {
223 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
227 } else if (f.isFile()) {
228 // regular file handling
229 if (!(types & TYPE_FILE)) {
233 // block device /fifo/char file, ignore
237 if (!nameFilter.empty()) {
238 int nameLen = strlen(entry->d_name);
239 if (nameLen < filterLen) {
240 continue; // name is shorter than the filter
243 char* nameSuffix = entry->d_name + (nameLen - filterLen);
244 if (strcmp(nameSuffix, nameFilter.c_str())) {
249 // passed all criteria, add to our result vector
250 result.push_back(file(entry->d_name));
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);
263 bool Dir::isEmpty() const
267 WIN32_FIND_DATA fData;
268 HANDLE find = FindFirstFile("\\*", &fData);
269 if (find == INVALID_HANDLE_VALUE) {
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
276 for (; !done; done = (FindNextFile(find, &fData) == 0)) {
277 if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
278 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
289 DIR* dp = opendir(_path.c_str());
295 struct dirent* entry = readdir(dp);
297 break; // done iteration
300 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
312 bool Dir::exists() const
314 return _path.isDir();
317 SGPath Dir::file(const std::string& name) const
319 SGPath childPath = _path;
320 childPath.set_cached(true);
321 childPath.append(name);
326 # define sgMkDir(d,m) _mkdir(d)
328 # define sgMkDir(d,m) mkdir(d,m)
331 bool Dir::create(mode_t mode)
334 return false; // already exists
337 // recursively create parent directories
339 if (!pr.path().isNull() && !pr.exists()) {
340 bool ok = pr.create(mode);
346 // finally, create ourselves
347 int err = sgMkDir(_path.c_str(), mode);
349 SG_LOG(SG_IO, SG_WARN, "directory creation failed: (" << _path.str() << ") " << strerror(errno) );
355 bool Dir::removeChildren() const
358 PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
359 BOOST_FOREACH(SGPath path, cs) {
362 ok = childDir.remove(true);
368 SG_LOG(SG_IO, SG_WARN, "failed to remove:" << path);
371 } // of child iteration
376 bool Dir::remove(bool recursive)
379 SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path);
384 if (!removeChildren()) {
387 } // of recursive deletion
390 int err = _rmdir(_path.c_str());
392 int err = rmdir(_path.c_str());
395 SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path.str() << ":" << strerror(errno));
400 Dir Dir::parent() const
402 return Dir(_path.dir());
405 } // of namespace simgear