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.utf8Str())),
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) throw 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 std::string s = p.local8BitStr();
119 ::snprintf(buf, 1024, "%s", s.c_str());
121 SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
125 return Dir(SGPath(buf));
127 SGPath p(tempnam(0, templ.c_str()));
129 if (!t.create(0700)) {
130 SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p);
137 static bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
139 return p1.file() < p2.file();
142 PathList Dir::children(int types, const std::string& nameFilter) const
146 types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
150 std::string search(_path.local8BitStr());
151 if (nameFilter.empty()) {
152 search += "\\*"; // everything
154 search += "\\*" + nameFilter;
157 WIN32_FIND_DATA fData;
158 HANDLE find = FindFirstFile(search.c_str(), &fData);
159 if (find == INVALID_HANDLE_VALUE) {
160 int err = GetLastError();
161 if (err != ERROR_FILE_NOT_FOUND) {
162 SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: FindFirstFile failed:" <<
163 _path << " with error:" << err);
169 for (bool done = false; !done; done = (FindNextFile(find, &fData) == 0)) {
170 if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
171 if (!(types & INCLUDE_HIDDEN)) {
176 if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
177 if (types & NO_DOT_OR_DOTDOT) {
178 if (!strcmp(fData.cFileName,".") || !strcmp(fData.cFileName,"..")) {
183 if (!(types & TYPE_DIR)) {
186 } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
187 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
189 continue; // always ignore device files
190 } else if (!(types & TYPE_FILE)) {
194 result.push_back(file(fData.cFileName));
199 std::string ps = _path.local8BitStr();
200 DIR* dp = opendir(ps.c_str());
202 SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path);
206 int filterLen = nameFilter.size();
209 struct dirent* entry = readdir(dp);
211 break; // done iteration
214 // skip hidden files (names beginning with '.') unless requested
215 if (!(types & INCLUDE_HIDDEN) && (entry->d_name[0] == '.') &&
216 strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
220 SGPath f = file(entry->d_name);
222 continue; // stat() failed
226 // directory handling
227 if (!(types & TYPE_DIR)) {
231 if (types & NO_DOT_OR_DOTDOT) {
232 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
236 } else if (f.isFile()) {
237 // regular file handling
238 if (!(types & TYPE_FILE)) {
242 // block device /fifo/char file, ignore
246 if (!nameFilter.empty()) {
247 int nameLen = strlen(entry->d_name);
248 if (nameLen < filterLen) {
249 continue; // name is shorter than the filter
252 char* nameSuffix = entry->d_name + (nameLen - filterLen);
253 if (strcmp(nameSuffix, nameFilter.c_str())) {
258 // passed all criteria, add to our result vector
259 result.push_back(file(entry->d_name));
265 // File system order is random. Make things deterministic,
266 // so it's the same for every user.
267 std::sort(result.begin(), result.end(), pathSortPredicate);
272 bool Dir::isEmpty() const
274 std::string ps = _path.local8BitStr();
276 return PathIsDirectoryEmpty( ps.c_str() );
278 DIR* dp = opendir( ps.c_str() );
279 if (!dp) return true;
283 while( (d = readdir(dp)) !=NULL && (n < 4) ) n++;
286 return (n == 2); // '.' and '..' always exist
290 bool Dir::exists() const
292 return _path.isDir();
295 SGPath Dir::file(const std::string& name) const
297 SGPath childPath = _path;
298 childPath.set_cached(true);
299 childPath.append(name);
304 # define sgMkDir(d,m) _mkdir(d)
306 # define sgMkDir(d,m) mkdir(d,m)
309 bool Dir::create(mode_t mode)
312 return false; // already exists
315 // recursively create parent directories
317 if (!pr.path().isNull() && !pr.exists()) {
318 bool ok = pr.create(mode);
324 // finally, create ourselves
325 std::string ps = _path.local8BitStr();
326 int err = sgMkDir(ps.c_str(), mode);
328 SG_LOG(SG_IO, SG_WARN, "directory creation failed: (" << _path << ") " << strerror(errno) );
334 bool Dir::removeChildren() const
337 PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
338 BOOST_FOREACH(SGPath path, cs) {
341 ok = childDir.remove(true);
347 SG_LOG(SG_IO, SG_WARN, "failed to remove:" << path);
350 } // of child iteration
355 bool Dir::remove(bool recursive)
358 SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path);
363 if (!removeChildren()) {
364 SG_LOG(SG_IO, SG_WARN, "Dir at:" << _path << " failed to remove children");
367 } // of recursive deletion
369 std::string ps = _path.local8BitStr();
371 int err = _rmdir(ps.c_str());
373 int err = rmdir(ps.c_str());
376 SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path << ":" << strerror(errno));
381 Dir Dir::parent() const
383 return Dir(_path.dir());
386 } // of namespace simgear