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.
21 #include <simgear_config.h>
22 #include <simgear/compiler.h>
24 #include <simgear/misc/sg_dir.hxx>
25 #include <simgear/structure/exception.hxx>
31 # define WIN32_LEAN_AND_MEAN
36 # include <sys/types.h>
38 # include <sys/stat.h>
43 #include <simgear/misc/strutils.hxx>
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;
90 #if defined(SG_WINDOWS)
91 wchar_t* buf = _wgetcwd(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 #if defined(SG_WINDOWS)
128 std::wstring wideTemplate = simgear::strutils::convertUtf8ToWString(templ);
129 wchar_t* buf = _wtempnam(0, wideTemplate.c_str());
131 free(buf); // unlike tempnam(), _wtempnam mallocs its result buffer
133 SGPath p(tempnam(0, templ.c_str()));
136 if (!t.create(0700)) {
137 SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p);
144 static bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
146 return p1.file() < p2.file();
149 PathList Dir::children(int types, const std::string& nameFilter) const
153 types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
156 #if defined(SG_WINDOWS)
157 std::wstring search(_path.wstr());
158 if (nameFilter.empty()) {
159 search += simgear::strutils::convertUtf8ToWString("\\*"); // everything
161 search += simgear::strutils::convertUtf8ToWString("\\*" + nameFilter);
164 WIN32_FIND_DATAW fData;
165 HANDLE find = FindFirstFileW(search.c_str(), &fData);
166 if (find == INVALID_HANDLE_VALUE) {
167 int err = GetLastError();
168 if (err != ERROR_FILE_NOT_FOUND) {
169 SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: FindFirstFile failed:" <<
170 _path << " with error:" << err);
176 for (bool done = false; !done; done = (FindNextFileW(find, &fData) == 0)) {
177 if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
178 if (!(types & INCLUDE_HIDDEN)) {
183 std::string utf8File = simgear::strutils::convertWStringToUtf8(fData.cFileName);
184 if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
185 if (types & NO_DOT_OR_DOTDOT) {
186 if ((utf8File == ".") || (utf8File == "..")) {
191 if (!(types & TYPE_DIR)) {
194 } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
195 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
197 continue; // always ignore device files
198 } else if (!(types & TYPE_FILE)) {
202 result.push_back(file(utf8File));
207 std::string ps = _path.local8BitStr();
208 DIR* dp = opendir(ps.c_str());
210 SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path);
214 int filterLen = nameFilter.size();
217 struct dirent* entry = readdir(dp);
219 break; // done iteration
222 // skip hidden files (names beginning with '.') unless requested
223 if (!(types & INCLUDE_HIDDEN) && (entry->d_name[0] == '.') &&
224 strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
228 SGPath f = file(entry->d_name);
230 continue; // stat() failed
234 // directory handling
235 if (!(types & TYPE_DIR)) {
239 if (types & NO_DOT_OR_DOTDOT) {
240 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
244 } else if (f.isFile()) {
245 // regular file handling
246 if (!(types & TYPE_FILE)) {
250 // block device /fifo/char file, ignore
254 if (!nameFilter.empty()) {
255 int nameLen = strlen(entry->d_name);
256 if (nameLen < filterLen) {
257 continue; // name is shorter than the filter
260 char* nameSuffix = entry->d_name + (nameLen - filterLen);
261 if (strcmp(nameSuffix, nameFilter.c_str())) {
266 // passed all criteria, add to our result vector
267 result.push_back(file(entry->d_name));
273 // File system order is random. Make things deterministic,
274 // so it's the same for every user.
275 std::sort(result.begin(), result.end(), pathSortPredicate);
280 bool Dir::isEmpty() const
282 #if defined(SG_WINDOWS)
283 std::wstring ps = _path.wstr();
284 return PathIsDirectoryEmptyW( ps.c_str() );
286 std::string ps = _path.local8BitStr();
287 DIR* dp = opendir( ps.c_str() );
288 if (!dp) return true;
292 while( (d = readdir(dp)) !=NULL && (n < 4) ) n++;
295 return (n == 2); // '.' and '..' always exist
299 bool Dir::exists() const
301 return _path.isDir();
304 SGPath Dir::file(const std::string& name) const
306 SGPath childPath = _path;
307 childPath.set_cached(true);
308 childPath.append(name);
312 bool Dir::create(mode_t mode)
315 return false; // already exists
318 // recursively create parent directories
320 if (!pr.path().isNull() && !pr.exists()) {
321 bool ok = pr.create(mode);
327 // finally, create ourselves
328 #if defined(SG_WINDOWS)
329 std::wstring ps = _path.wstr();
330 int err = _wmkdir(ps.c_str());
332 std::string ps = _path.local8BitStr();
333 int err = mkdir(ps.c_str(), mode);
336 SG_LOG(SG_IO, SG_WARN, "directory creation failed: (" << _path << ") " << strerror(errno) );
342 bool Dir::removeChildren() const
345 PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
346 BOOST_FOREACH(SGPath path, cs) {
349 ok = childDir.remove(true);
355 SG_LOG(SG_IO, SG_WARN, "failed to remove:" << path);
358 } // of child iteration
363 bool Dir::remove(bool recursive)
366 SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path);
371 if (!removeChildren()) {
372 SG_LOG(SG_IO, SG_WARN, "Dir at:" << _path << " failed to remove children");
375 } // of recursive deletion
377 #if defined(SG_WINDOWS)
378 std::wstring ps = _path.wstr();
379 int err = _wrmdir(ps.c_str());
381 std::string ps = _path.local8BitStr();
382 int err = rmdir(ps.c_str());
385 SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path << ":" << strerror(errno));
390 Dir Dir::parent() const
392 return Dir(_path.dir());
395 } // of namespace simgear