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
36 # include <sys/types.h>
38 # include <sys/stat.h>
43 #include <simgear/debug/logstream.hxx>
44 #include <boost/foreach.hpp>
49 #include <algorithm> // for std::sort
57 _removeOnDestroy(false)
61 Dir::Dir(const SGPath& path) :
63 _removeOnDestroy(false)
65 _path.set_cached(false); // disable caching, so create/remove work
68 Dir::Dir(const Dir& rel, const SGPath& relPath) :
69 _path(rel.file(relPath.str())),
70 _removeOnDestroy(false)
72 _path.set_cached(false); // disable caching, so create/remove work
77 if (_removeOnDestroy) {
82 void Dir::setRemoveOnDestroy()
84 _removeOnDestroy = true;
91 char* buf = _getcwd(NULL, 0);
93 char *buf = ::getcwd(NULL, 0);
96 if (errno == 2) sg_exception("The current directory is invalid");
97 else throw sg_exception(strerror(errno));
105 Dir Dir::tempDir(const std::string& templ)
109 const char* tempPath = ::getenv("TMPDIR");
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
118 ::snprintf(buf, 1024, "%s", p.c_str());
120 SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
124 return Dir(SGPath(buf));
126 SGPath p(tempnam(0, templ.c_str()));
128 if (!t.create(0700)) {
129 SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p.str());
136 static bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
138 return p1.file() < p2.file();
141 PathList Dir::children(int types, const std::string& nameFilter) const
145 types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
149 std::string search(_path.str());
150 if (nameFilter.empty()) {
151 search += "\\*"; // everything
153 search += "\\*" + nameFilter;
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);
168 for (bool done = false; !done; done = (FindNextFile(find, &fData) == 0)) {
169 if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
170 if (!(types & INCLUDE_HIDDEN)) {
175 if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
176 if (types & NO_DOT_OR_DOTDOT) {
177 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
182 if (!(types & TYPE_DIR)) {
185 } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
186 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
188 continue; // always ignore device files
189 } else if (!(types & TYPE_FILE)) {
193 result.push_back(file(fData.cFileName));
198 DIR* dp = opendir(_path.c_str());
200 SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path.str());
204 int filterLen = nameFilter.size();
207 struct dirent* entry = readdir(dp);
209 break; // done iteration
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, "..")) {
218 SGPath f = file(entry->d_name);
220 continue; // stat() failed
224 // directory handling
225 if (!(types & TYPE_DIR)) {
229 if (types & NO_DOT_OR_DOTDOT) {
230 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
234 } else if (f.isFile()) {
235 // regular file handling
236 if (!(types & TYPE_FILE)) {
240 // block device /fifo/char file, ignore
244 if (!nameFilter.empty()) {
245 int nameLen = strlen(entry->d_name);
246 if (nameLen < filterLen) {
247 continue; // name is shorter than the filter
250 char* nameSuffix = entry->d_name + (nameLen - filterLen);
251 if (strcmp(nameSuffix, nameFilter.c_str())) {
256 // passed all criteria, add to our result vector
257 result.push_back(file(entry->d_name));
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);
270 bool Dir::isEmpty() const
274 WIN32_FIND_DATA fData;
275 HANDLE find = FindFirstFile("\\*", &fData);
276 if (find == INVALID_HANDLE_VALUE) {
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
283 for (; !done; done = (FindNextFile(find, &fData) == 0)) {
284 if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
285 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
296 DIR* dp = opendir(_path.c_str());
302 struct dirent* entry = readdir(dp);
304 break; // done iteration
307 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
319 bool Dir::exists() const
321 return _path.isDir();
324 SGPath Dir::file(const std::string& name) const
326 SGPath childPath = _path;
327 childPath.set_cached(true);
328 childPath.append(name);
333 # define sgMkDir(d,m) _mkdir(d)
335 # define sgMkDir(d,m) mkdir(d,m)
338 bool Dir::create(mode_t mode)
341 return false; // already exists
344 // recursively create parent directories
346 if (!pr.path().isNull() && !pr.exists()) {
347 bool ok = pr.create(mode);
353 // finally, create ourselves
354 int err = sgMkDir(_path.c_str(), mode);
356 SG_LOG(SG_IO, SG_WARN, "directory creation failed: (" << _path.str() << ") " << strerror(errno) );
362 bool Dir::removeChildren() const
365 PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
366 BOOST_FOREACH(SGPath path, cs) {
369 ok = childDir.remove(true);
375 SG_LOG(SG_IO, SG_WARN, "failed to remove:" << path);
378 } // of child iteration
383 bool Dir::remove(bool recursive)
386 SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path);
391 if (!removeChildren()) {
392 SG_LOG(SG_IO, SG_WARN, "Dir at:" << _path << " failed to remove children");
395 } // of recursive deletion
398 int err = _rmdir(_path.c_str());
400 int err = rmdir(_path.c_str());
403 SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path.str() << ":" << strerror(errno));
408 Dir Dir::parent() const
410 return Dir(_path.dir());
413 } // of namespace simgear