Merge "Merge remote-tracking branch 'gerrit/release-4-6'"
[alexxy/gromacs.git] / src / gromacs / utility / file.cpp
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11  * Copyright (c) 2001-2009, The GROMACS development team,
12  * check out http://www.gromacs.org for more information.
13  *
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * If you want to redistribute modifications, please consider that
20  * scientific software is very special. Version control is crucial -
21  * bugs must be traceable. We will be happy to consider code for
22  * inclusion in the official distribution, but derived work must not
23  * be called official GROMACS. Details are found in the README & COPYING
24  * files - if they are missing, get the official version at www.gromacs.org.
25  *
26  * To help us fund GROMACS development, we humbly ask that you cite
27  * the papers on the package - you can find them in the top README file.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \internal \file
32  * \brief
33  * Implements gmx::File.
34  *
35  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
36  * \ingroup module_utility
37  */
38 #include "file.h"
39
40 #include <cerrno>
41 #include <cstdio>
42 #include <cstring>
43
44 #include <algorithm>
45 #include <string>
46 #include <vector>
47
48 #include "gromacs/utility/exceptions.h"
49 #include "gromacs/utility/gmxassert.h"
50 #include "gromacs/utility/stringutil.h"
51
52 namespace gmx
53 {
54
55 /*! \internal \brief
56  * Private implementation class for File.
57  *
58  * \ingroup module_utility
59  */
60 class File::Impl
61 {
62     public:
63         /*! \brief
64          * Initialize a file object with the given handle.
65          *
66          * \param[in]  fp     File handle to use (may be NULL).
67          * \param[in]  bClose Whether this object should close its file handle.
68          */
69         Impl(FILE *fp, bool bClose);
70         ~Impl();
71
72         //! File handle for this object (may be NULL).
73         FILE                   *fp_;
74         /*! \brief
75          * Whether \p fp_ should be closed by this object.
76          *
77          * Can be true if \p fp_ is NULL.
78          */
79         bool                    bClose_;
80 };
81
82 File::Impl::Impl(FILE *fp, bool bClose)
83     : fp_(fp), bClose_(bClose)
84 {
85 }
86
87 File::Impl::~Impl()
88 {
89     if (fp_ != NULL && bClose_)
90     {
91         if (fclose(fp_) != 0)
92         {
93             // TODO: Log the error somewhere
94         }
95     }
96 }
97
98 File::File(const char *filename, const char *mode)
99     : impl_(new Impl(NULL, true))
100 {
101     open(filename, mode);
102 }
103
104 File::File(const std::string &filename, const char *mode)
105     : impl_(new Impl(NULL, true))
106 {
107     open(filename, mode);
108 }
109
110 File::File(FILE *fp, bool bClose)
111     : impl_(new Impl(fp, bClose))
112 {
113 }
114
115 File::~File()
116 {
117 }
118
119 void File::open(const char *filename, const char *mode)
120 {
121     GMX_RELEASE_ASSERT(impl_->fp_ == NULL,
122                        "Attempted to open the same file object twice");
123     // TODO: Port all necessary functionality from ffopen() here.
124     impl_->fp_ = fopen(filename, mode);
125     if (impl_->fp_ == NULL)
126     {
127         GMX_THROW_WITH_ERRNO(
128                 FileIOError(formatString("Could not open file '%s'", filename)),
129                 "fopen", errno);
130     }
131 }
132
133 void File::open(const std::string &filename, const char *mode)
134 {
135     open(filename.c_str(), mode);
136 }
137
138 void File::close()
139 {
140     GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
141                        "Attempted to close a file object that is not open");
142     GMX_RELEASE_ASSERT(impl_->bClose_,
143                        "Attempted to close a file object that should not be");
144     bool bOk = (fclose(impl_->fp_) == 0);
145     impl_->fp_ = NULL;
146     if (!bOk)
147     {
148         GMX_THROW_WITH_ERRNO(
149                 FileIOError("Error while closing file"), "fclose", errno);
150     }
151 }
152
153 FILE *File::handle()
154 {
155     GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
156                        "Attempted to access a file object that is not open");
157     return impl_->fp_;
158 }
159
160 void File::readBytes(void *buffer, size_t bytes)
161 {
162     errno = 0;
163     FILE *fp = handle();
164     // TODO: Retry based on errno or something else?
165     size_t bytesRead = std::fread(buffer, 1, bytes, fp);
166     if (bytesRead != bytes)
167     {
168         if (feof(fp))
169         {
170             GMX_THROW(FileIOError(
171                         formatString("Premature end of file\n"
172                                      "Attempted to read: %d bytes\n"
173                                      "Successfully read: %d bytes",
174                                      static_cast<int>(bytes),
175                                      static_cast<int>(bytesRead))));
176         }
177         else
178         {
179             GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
180                                  "fread", errno);
181         }
182     }
183 }
184
185 bool File::readLine(std::string *line)
186 {
187     line->clear();
188     const size_t bufsize = 256;
189     std::string result;
190     char buf[bufsize];
191     buf[0] = '\0';
192     FILE *fp = handle();
193     while (fgets(buf, bufsize, fp) != NULL)
194     {
195         size_t length = std::strlen(buf);
196         result.append(buf, length);
197         if (length < bufsize - 1 || buf[length - 1] == '\n')
198         {
199             break;
200         }
201     }
202     if (ferror(fp))
203     {
204         GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
205                              "fgets", errno);
206     }
207     *line = result;
208     return !result.empty() || !feof(fp);
209 }
210
211 void File::writeString(const char *str)
212 {
213     if (fprintf(handle(), "%s", str) < 0)
214     {
215         GMX_THROW_WITH_ERRNO(FileIOError("Writing to file failed"),
216                              "fprintf", errno);
217     }
218 }
219
220 void File::writeLine(const char *line)
221 {
222     size_t length = std::strlen(line);
223
224     writeString(line);
225     if (length == 0 || line[length-1] != '\n')
226     {
227         writeString("\n");
228     }
229 }
230
231 void File::writeLine()
232 {
233     writeString("\n");
234 }
235
236 // static
237 File &File::standardInput()
238 {
239     static File stdinObject(stdin, false);
240     return stdinObject;
241 }
242
243 // static
244 File &File::standardOutput()
245 {
246     static File stdoutObject(stdout, false);
247     return stdoutObject;
248 }
249
250 // static
251 File &File::standardError()
252 {
253     static File stderrObject(stderr, false);
254     return stderrObject;
255 }
256
257 // static
258 std::string File::readToString(const char *filename)
259 {
260     // Binary mode is required on Windows to be able to determine a size
261     // that can be passed to fread().
262     File file(filename, "rb");
263     FILE *fp = file.handle();
264
265     if (std::fseek(fp, 0L, SEEK_END) != 0)
266     {
267         GMX_THROW_WITH_ERRNO(FileIOError("Seeking to end of file failed"),
268                              "fseek", errno);
269     }
270     long len = std::ftell(fp);
271     if (len == -1)
272     {
273         GMX_THROW_WITH_ERRNO(FileIOError("Reading file length failed"),
274                              "ftell", errno);
275     }
276     if (std::fseek(fp, 0L, SEEK_SET) != 0)
277     {
278         GMX_THROW_WITH_ERRNO(FileIOError("Seeking to start of file failed"),
279                              "fseek", errno);
280     }
281
282     std::vector<char> data(len);
283     file.readBytes(&data[0], len);
284     file.close();
285
286     std::string result(&data[0], len);
287     // The below is necessary on Windows to make newlines stay as '\n' on a
288     // roundtrip.
289     result = replaceAll(result, "\r\n", "\n");
290
291     return result;
292 }
293
294 // static
295 std::string File::readToString(const std::string &filename)
296 {
297     return readToString(filename.c_str());
298 }
299
300 } // namespace gmx