2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012, by the GROMACS development team, led by
5 * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6 * others, as listed in the AUTHORS file in the top-level source
7 * 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
52 #include "gromacs/legacyheaders/futil.h"
54 #include "gromacs/utility/exceptions.h"
55 #include "gromacs/utility/gmxassert.h"
56 #include "gromacs/utility/stringutil.h"
62 * Private implementation class for File.
64 * \ingroup module_utility
70 * Initialize a file object with the given handle.
72 * \param[in] fp File handle to use (may be NULL).
73 * \param[in] bClose Whether this object should close its file handle.
75 Impl(FILE *fp, bool bClose);
78 //! File handle for this object (may be NULL).
81 * Whether \p fp_ should be closed by this object.
83 * Can be true if \p fp_ is NULL.
88 File::Impl::Impl(FILE *fp, bool bClose)
89 : fp_(fp), bClose_(bClose)
95 if (fp_ != NULL && bClose_)
99 // TODO: Log the error somewhere
104 File::File(const char *filename, const char *mode)
105 : impl_(new Impl(NULL, true))
107 open(filename, mode);
110 File::File(const std::string &filename, const char *mode)
111 : impl_(new Impl(NULL, true))
113 open(filename, mode);
116 File::File(FILE *fp, bool bClose)
117 : impl_(new Impl(fp, bClose))
125 void File::open(const char *filename, const char *mode)
127 GMX_RELEASE_ASSERT(impl_->fp_ == NULL,
128 "Attempted to open the same file object twice");
129 // TODO: Port all necessary functionality from ffopen() here.
130 impl_->fp_ = fopen(filename, mode);
131 if (impl_->fp_ == NULL)
133 GMX_THROW_WITH_ERRNO(
134 FileIOError(formatString("Could not open file '%s'", filename)),
139 void File::open(const std::string &filename, const char *mode)
141 open(filename.c_str(), mode);
146 GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
147 "Attempted to close a file object that is not open");
148 GMX_RELEASE_ASSERT(impl_->bClose_,
149 "Attempted to close a file object that should not be");
150 bool bOk = (fclose(impl_->fp_) == 0);
154 GMX_THROW_WITH_ERRNO(
155 FileIOError("Error while closing file"), "fclose", errno);
161 GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
162 "Attempted to access a file object that is not open");
166 void File::readBytes(void *buffer, size_t bytes)
170 // TODO: Retry based on errno or something else?
171 size_t bytesRead = std::fread(buffer, 1, bytes, fp);
172 if (bytesRead != bytes)
176 GMX_THROW(FileIOError(
177 formatString("Premature end of file\n"
178 "Attempted to read: %d bytes\n"
179 "Successfully read: %d bytes",
180 static_cast<int>(bytes),
181 static_cast<int>(bytesRead))));
185 GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
191 bool File::readLine(std::string *line)
194 const size_t bufsize = 256;
199 while (fgets(buf, bufsize, fp) != NULL)
201 size_t length = std::strlen(buf);
202 result.append(buf, length);
203 if (length < bufsize - 1 || buf[length - 1] == '\n')
210 GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
214 return !result.empty() || !feof(fp);
217 void File::writeString(const char *str)
219 if (fprintf(handle(), "%s", str) < 0)
221 GMX_THROW_WITH_ERRNO(FileIOError("Writing to file failed"),
226 void File::writeLine(const char *line)
228 size_t length = std::strlen(line);
231 if (length == 0 || line[length-1] != '\n')
237 void File::writeLine()
243 bool File::exists(const char *filename)
245 return gmx_fexist(filename);
249 bool File::exists(const std::string &filename)
251 return exists(filename.c_str());
255 File &File::standardInput()
257 static File stdinObject(stdin, false);
262 File &File::standardOutput()
264 static File stdoutObject(stdout, false);
269 File &File::standardError()
271 static File stderrObject(stderr, false);
276 std::string File::readToString(const char *filename)
278 // Binary mode is required on Windows to be able to determine a size
279 // that can be passed to fread().
280 File file(filename, "rb");
281 FILE *fp = file.handle();
283 if (std::fseek(fp, 0L, SEEK_END) != 0)
285 GMX_THROW_WITH_ERRNO(FileIOError("Seeking to end of file failed"),
288 long len = std::ftell(fp);
291 GMX_THROW_WITH_ERRNO(FileIOError("Reading file length failed"),
294 if (std::fseek(fp, 0L, SEEK_SET) != 0)
296 GMX_THROW_WITH_ERRNO(FileIOError("Seeking to start of file failed"),
300 std::vector<char> data(len);
301 file.readBytes(&data[0], len);
304 std::string result(&data[0], len);
305 // The below is necessary on Windows to make newlines stay as '\n' on a
307 result = replaceAll(result, "\r\n", "\n");
313 std::string File::readToString(const std::string &filename)
315 return readToString(filename.c_str());
319 void File::writeFileFromString(const std::string &filename,
320 const std::string &text)
322 File file(filename, "w");
323 file.writeString(text);