Merge branch release-2016 into release-2018
[gromacs.git] / src / gromacs / utility / directoryenumerator.cpp
blob230f456be8bcdb8049633f3fc6587923cc9e9d8e
1 /*
2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2010,2011,2014,2015,2016,2017, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
35 /*! \internal \file
36 * \brief
37 * Implements gmx::DirectoryEnumerator.
39 * \author Erik Lindahl (original C implementation)
40 * \author Teemu Murtola <teemu.murtola@gmail.com> (C++ wrapper + errno handling)
41 * \ingroup module_utility
43 #include "gmxpre.h"
45 #include "directoryenumerator.h"
47 #include "config.h"
49 #include <cerrno>
50 #include <cstdio>
52 #include <algorithm>
53 #include <string>
54 #include <vector>
56 #if HAVE_DIRENT_H
57 #include <dirent.h>
58 #endif
59 #if GMX_NATIVE_WINDOWS
60 #include <io.h>
61 #endif
63 #include "gromacs/utility/exceptions.h"
64 #include "gromacs/utility/fatalerror.h"
65 #include "gromacs/utility/futil.h"
66 #include "gromacs/utility/gmxassert.h"
67 #include "gromacs/utility/smalloc.h"
68 #include "gromacs/utility/stringutil.h"
70 namespace gmx
73 /********************************************************************
74 * DirectoryEnumerator::Impl
77 // TODO: Consider whether checking the return value of closing would be useful,
78 // and what could we do if it fails?
79 #if GMX_NATIVE_WINDOWS
80 // TODO: Consider if Windows provides more error details through other APIs.
81 class DirectoryEnumerator::Impl
83 public:
84 static Impl *init(const char *dirname, bool bThrow)
86 std::string tmpname(dirname);
87 // Remove possible trailing directory separator.
88 // TODO: Use a method in gmx::Path instead.
89 if (tmpname.back() == '/' || tmpname.back() == '\\')
91 tmpname.pop_back();
94 // Add wildcard.
95 tmpname.append("/*");
97 errno = 0;
98 _finddata_t finddata;
99 intptr_t handle = _findfirst(tmpname.c_str(), &finddata);
100 if (handle < 0L)
102 if (errno != ENOENT && bThrow)
104 const int code = errno;
105 const std::string message =
106 formatString("Failed to list files in directory '%s'",
107 dirname);
108 GMX_THROW_WITH_ERRNO(FileIOError(message), "_findfirst", code);
110 return NULL;
112 return new Impl(handle, finddata);
114 Impl(intptr_t handle, _finddata_t finddata)
115 : windows_handle(handle), finddata(finddata), bFirst_(true)
118 ~Impl()
120 _findclose(windows_handle);
123 bool nextFile(std::string *filename)
125 if (bFirst_)
127 *filename = finddata.name;
128 bFirst_ = false;
129 return true;
131 else
133 errno = 0;
134 if (_findnext(windows_handle, &finddata) != 0)
136 if (errno == 0 || errno == ENOENT)
138 filename->clear();
139 return false;
141 else
143 GMX_THROW_WITH_ERRNO(
144 FileIOError("Failed to list files in a directory"),
145 "_findnext", errno);
148 *filename = finddata.name;
149 return true;
153 private:
154 intptr_t windows_handle;
155 _finddata_t finddata;
156 bool bFirst_;
158 #elif HAVE_DIRENT_H
159 class DirectoryEnumerator::Impl
161 public:
162 static Impl *init(const char *dirname, bool bThrow)
164 errno = 0;
165 DIR *handle = opendir(dirname);
166 if (handle == nullptr)
168 if (bThrow)
170 const int code = errno;
171 const std::string message =
172 formatString("Failed to list files in directory '%s'",
173 dirname);
174 GMX_THROW_WITH_ERRNO(FileIOError(message), "opendir", code);
176 return nullptr;
178 return new Impl(handle);
180 explicit Impl(DIR *handle) : dirent_handle(handle) {}
181 ~Impl()
183 closedir(dirent_handle);
186 bool nextFile(std::string *filename)
188 errno = 0;
189 dirent *p = readdir(dirent_handle);
190 if (p == nullptr)
192 if (errno == 0)
194 // All the files have been found.
195 filename->clear();
196 return false;
198 else
200 GMX_THROW_WITH_ERRNO(
201 FileIOError("Failed to list files in a directory"),
202 "readdir", errno);
205 *filename = p->d_name;
206 return true;
209 private:
210 DIR *dirent_handle;
212 #else
213 class DirectoryEnumerator::Impl
215 public:
216 static Impl *init(const char * /*dirname*/, bool /*bThrow*/)
218 std::string message(
219 "Source compiled without POSIX dirent or Windows support "
220 "- cannot scan directories. In the very unlikely event "
221 "this is not a compile-time mistake you could consider "
222 "implementing support for your platform in "
223 "directoryenumerator.cpp, but contact the developers "
224 "to make sure it's really necessary!");
225 GMX_THROW(NotImplementedError(message));
228 bool nextFile(std::string * /*filename*/)
230 return false;
233 #endif
235 /********************************************************************
236 * DirectoryEnumerator
239 // static
240 std::vector<std::string>
241 DirectoryEnumerator::enumerateFilesWithExtension(
242 const char *dirname, const char *extension, bool bThrow)
244 std::vector<std::string> result;
245 DirectoryEnumerator dir(dirname, bThrow);
246 std::string nextName;
247 while (dir.nextFile(&nextName))
249 if (debug)
251 std::fprintf(debug, "dir '%s' file '%s'\n",
252 dirname, nextName.c_str());
254 // TODO: What about case sensitivity?
255 if (endsWith(nextName, extension))
257 result.push_back(nextName);
261 std::sort(result.begin(), result.end());
262 return result;
266 DirectoryEnumerator::DirectoryEnumerator(const char *dirname, bool bThrow)
267 : impl_(nullptr)
269 GMX_RELEASE_ASSERT(dirname != nullptr && dirname[0] != '\0',
270 "Attempted to open empty/null directory path");
271 impl_.reset(Impl::init(dirname, bThrow));
274 DirectoryEnumerator::DirectoryEnumerator(const std::string &dirname, bool bThrow)
275 : impl_(nullptr)
277 GMX_RELEASE_ASSERT(!dirname.empty(),
278 "Attempted to open empty/null directory path");
279 impl_.reset(Impl::init(dirname.c_str(), bThrow));
282 DirectoryEnumerator::~DirectoryEnumerator()
286 bool DirectoryEnumerator::nextFile(std::string *filename)
288 if (impl_ == nullptr)
290 filename->clear();
291 return false;
293 return impl_->nextFile(filename);
296 } // namespace gmx