2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015, 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.
37 * Implements gmx::File.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_utility
62 #include "gromacs/utility/exceptions.h"
63 #include "gromacs/utility/gmxassert.h"
64 #include "gromacs/utility/stringutil.h"
70 * Private implementation class for File.
72 * \ingroup module_utility
78 * Initialize a file object with the given handle.
80 * \param[in] fp %File handle to use (may be NULL).
81 * \param[in] bClose Whether this object should close its file handle.
83 Impl(FILE *fp, bool bClose);
86 //! File handle for this object (may be NULL).
89 * Whether \p fp_ should be closed by this object.
91 * Can be true if \p fp_ is NULL.
96 File::Impl::Impl(FILE *fp, bool bClose)
97 : fp_(fp), bClose_(bClose)
103 if (fp_ != NULL && bClose_)
105 if (fclose(fp_) != 0)
107 // TODO: Log the error somewhere
113 FILE *File::openRawHandle(const char *filename, const char *mode)
115 FILE *fp = fopen(filename, mode);
118 GMX_THROW_WITH_ERRNO(
119 FileIOError(formatString("Could not open file '%s'", filename)),
126 FILE *File::openRawHandle(const std::string &filename, const char *mode)
128 return openRawHandle(filename.c_str(), mode);
131 File::File(const char *filename, const char *mode)
132 : impl_(new Impl(NULL, true))
134 open(filename, mode);
137 File::File(const std::string &filename, const char *mode)
138 : impl_(new Impl(NULL, true))
140 open(filename, mode);
143 File::File(FILE *fp, bool bClose)
144 : impl_(new Impl(fp, bClose))
152 void File::open(const char *filename, const char *mode)
154 GMX_RELEASE_ASSERT(impl_->fp_ == NULL,
155 "Attempted to open the same file object twice");
156 // TODO: Port all necessary functionality from gmx_ffopen() here.
157 impl_->fp_ = openRawHandle(filename, mode);
160 void File::open(const std::string &filename, const char *mode)
162 open(filename.c_str(), mode);
167 GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
168 "Attempted to close a file object that is not open");
169 GMX_RELEASE_ASSERT(impl_->bClose_,
170 "Attempted to close a file object that should not be");
171 bool bOk = (fclose(impl_->fp_) == 0);
175 GMX_THROW_WITH_ERRNO(
176 FileIOError("Error while closing file"), "fclose", errno);
180 bool File::isInteractive() const
182 GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
183 "Attempted to access a file object that is not open");
185 return isatty(fileno(impl_->fp_));
193 GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
194 "Attempted to access a file object that is not open");
198 void File::readBytes(void *buffer, size_t bytes)
202 // TODO: Retry based on errno or something else?
203 size_t bytesRead = std::fread(buffer, 1, bytes, fp);
204 if (bytesRead != bytes)
208 GMX_THROW(FileIOError(
209 formatString("Premature end of file\n"
210 "Attempted to read: %d bytes\n"
211 "Successfully read: %d bytes",
212 static_cast<int>(bytes),
213 static_cast<int>(bytesRead))));
217 GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
223 bool File::readLine(std::string *line)
225 if (!readLineWithTrailingSpace(line))
229 size_t endPos = line->find_last_not_of(" \t\r\n");
230 if (endPos != std::string::npos)
232 line->resize(endPos + 1);
237 bool File::readLineWithTrailingSpace(std::string *line)
240 const size_t bufsize = 256;
245 while (fgets(buf, bufsize, fp) != NULL)
247 size_t length = std::strlen(buf);
248 result.append(buf, length);
249 if (length < bufsize - 1 || buf[length - 1] == '\n')
256 GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
260 return !result.empty() || !feof(fp);
263 void File::writeString(const char *str)
265 if (fprintf(handle(), "%s", str) < 0)
267 GMX_THROW_WITH_ERRNO(FileIOError("Writing to file failed"),
272 void File::writeLine(const char *line)
274 size_t length = std::strlen(line);
277 if (length == 0 || line[length-1] != '\n')
283 void File::writeLine()
289 bool File::exists(const char *filename)
291 if (filename == NULL)
295 FILE *test = fopen(filename, "r");
303 // Windows doesn't allow fopen of directory, so we don't need to check
305 #ifndef GMX_NATIVE_WINDOWS
307 int status = stat(filename, &st_buf);
308 if (status != 0 || !S_ISREG(st_buf.st_mode))
318 bool File::exists(const std::string &filename)
320 return exists(filename.c_str());
324 File &File::standardInput()
326 static File stdinObject(stdin, false);
331 File &File::standardOutput()
333 static File stdoutObject(stdout, false);
338 File &File::standardError()
340 static File stderrObject(stderr, false);
345 std::string File::readToString(const char *filename)
347 // Binary mode is required on Windows to be able to determine a size
348 // that can be passed to fread().
349 File file(filename, "rb");
350 FILE *fp = file.handle();
352 if (std::fseek(fp, 0L, SEEK_END) != 0)
354 GMX_THROW_WITH_ERRNO(FileIOError("Seeking to end of file failed"),
357 long len = std::ftell(fp);
360 GMX_THROW_WITH_ERRNO(FileIOError("Reading file length failed"),
363 if (std::fseek(fp, 0L, SEEK_SET) != 0)
365 GMX_THROW_WITH_ERRNO(FileIOError("Seeking to start of file failed"),
369 std::vector<char> data(len);
370 file.readBytes(&data[0], len);
373 std::string result(&data[0], len);
374 // The below is necessary on Windows to make newlines stay as '\n' on a
376 result = replaceAll(result, "\r\n", "\n");
382 std::string File::readToString(const std::string &filename)
384 return readToString(filename.c_str());
388 void File::writeFileFromString(const std::string &filename,
389 const std::string &text)
391 File file(filename, "w");
392 file.writeString(text);