Merge release-4-6 into master
[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/legacyheaders/futil.h"
49
50 #include "gromacs/utility/exceptions.h"
51 #include "gromacs/utility/gmxassert.h"
52 #include "gromacs/utility/stringutil.h"
53
54 namespace gmx
55 {
56
57 /*! \internal \brief
58  * Private implementation class for File.
59  *
60  * \ingroup module_utility
61  */
62 class File::Impl
63 {
64     public:
65         /*! \brief
66          * Initialize a file object with the given handle.
67          *
68          * \param[in]  fp     File handle to use (may be NULL).
69          * \param[in]  bClose Whether this object should close its file handle.
70          */
71         Impl(FILE *fp, bool bClose);
72         ~Impl();
73
74         //! File handle for this object (may be NULL).
75         FILE                   *fp_;
76         /*! \brief
77          * Whether \p fp_ should be closed by this object.
78          *
79          * Can be true if \p fp_ is NULL.
80          */
81         bool                    bClose_;
82 };
83
84 File::Impl::Impl(FILE *fp, bool bClose)
85     : fp_(fp), bClose_(bClose)
86 {
87 }
88
89 File::Impl::~Impl()
90 {
91     if (fp_ != NULL && bClose_)
92     {
93         if (fclose(fp_) != 0)
94         {
95             // TODO: Log the error somewhere
96         }
97     }
98 }
99
100 File::File(const char *filename, const char *mode)
101     : impl_(new Impl(NULL, true))
102 {
103     open(filename, mode);
104 }
105
106 File::File(const std::string &filename, const char *mode)
107     : impl_(new Impl(NULL, true))
108 {
109     open(filename, mode);
110 }
111
112 File::File(FILE *fp, bool bClose)
113     : impl_(new Impl(fp, bClose))
114 {
115 }
116
117 File::~File()
118 {
119 }
120
121 void File::open(const char *filename, const char *mode)
122 {
123     GMX_RELEASE_ASSERT(impl_->fp_ == NULL,
124                        "Attempted to open the same file object twice");
125     // TODO: Port all necessary functionality from ffopen() here.
126     impl_->fp_ = fopen(filename, mode);
127     if (impl_->fp_ == NULL)
128     {
129         GMX_THROW_WITH_ERRNO(
130                 FileIOError(formatString("Could not open file '%s'", filename)),
131                 "fopen", errno);
132     }
133 }
134
135 void File::open(const std::string &filename, const char *mode)
136 {
137     open(filename.c_str(), mode);
138 }
139
140 void File::close()
141 {
142     GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
143                        "Attempted to close a file object that is not open");
144     GMX_RELEASE_ASSERT(impl_->bClose_,
145                        "Attempted to close a file object that should not be");
146     bool bOk = (fclose(impl_->fp_) == 0);
147     impl_->fp_ = NULL;
148     if (!bOk)
149     {
150         GMX_THROW_WITH_ERRNO(
151                 FileIOError("Error while closing file"), "fclose", errno);
152     }
153 }
154
155 FILE *File::handle()
156 {
157     GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
158                        "Attempted to access a file object that is not open");
159     return impl_->fp_;
160 }
161
162 void File::readBytes(void *buffer, size_t bytes)
163 {
164     errno = 0;
165     FILE *fp = handle();
166     // TODO: Retry based on errno or something else?
167     size_t bytesRead = std::fread(buffer, 1, bytes, fp);
168     if (bytesRead != bytes)
169     {
170         if (feof(fp))
171         {
172             GMX_THROW(FileIOError(
173                         formatString("Premature end of file\n"
174                                      "Attempted to read: %d bytes\n"
175                                      "Successfully read: %d bytes",
176                                      static_cast<int>(bytes),
177                                      static_cast<int>(bytesRead))));
178         }
179         else
180         {
181             GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
182                                  "fread", errno);
183         }
184     }
185 }
186
187 bool File::readLine(std::string *line)
188 {
189     line->clear();
190     const size_t bufsize = 256;
191     std::string result;
192     char buf[bufsize];
193     buf[0] = '\0';
194     FILE *fp = handle();
195     while (fgets(buf, bufsize, fp) != NULL)
196     {
197         size_t length = std::strlen(buf);
198         result.append(buf, length);
199         if (length < bufsize - 1 || buf[length - 1] == '\n')
200         {
201             break;
202         }
203     }
204     if (ferror(fp))
205     {
206         GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
207                              "fgets", errno);
208     }
209     *line = result;
210     return !result.empty() || !feof(fp);
211 }
212
213 void File::writeString(const char *str)
214 {
215     if (fprintf(handle(), "%s", str) < 0)
216     {
217         GMX_THROW_WITH_ERRNO(FileIOError("Writing to file failed"),
218                              "fprintf", errno);
219     }
220 }
221
222 void File::writeLine(const char *line)
223 {
224     size_t length = std::strlen(line);
225
226     writeString(line);
227     if (length == 0 || line[length-1] != '\n')
228     {
229         writeString("\n");
230     }
231 }
232
233 void File::writeLine()
234 {
235     writeString("\n");
236 }
237
238 // static
239 bool File::exists(const char *filename)
240 {
241     return gmx_fexist(filename);
242 }
243
244 // static
245 bool File::exists(const std::string &filename)
246 {
247     return exists(filename.c_str());
248 }
249
250 // static
251 File &File::standardInput()
252 {
253     static File stdinObject(stdin, false);
254     return stdinObject;
255 }
256
257 // static
258 File &File::standardOutput()
259 {
260     static File stdoutObject(stdout, false);
261     return stdoutObject;
262 }
263
264 // static
265 File &File::standardError()
266 {
267     static File stderrObject(stderr, false);
268     return stderrObject;
269 }
270
271 // static
272 std::string File::readToString(const char *filename)
273 {
274     // Binary mode is required on Windows to be able to determine a size
275     // that can be passed to fread().
276     File file(filename, "rb");
277     FILE *fp = file.handle();
278
279     if (std::fseek(fp, 0L, SEEK_END) != 0)
280     {
281         GMX_THROW_WITH_ERRNO(FileIOError("Seeking to end of file failed"),
282                              "fseek", errno);
283     }
284     long len = std::ftell(fp);
285     if (len == -1)
286     {
287         GMX_THROW_WITH_ERRNO(FileIOError("Reading file length failed"),
288                              "ftell", errno);
289     }
290     if (std::fseek(fp, 0L, SEEK_SET) != 0)
291     {
292         GMX_THROW_WITH_ERRNO(FileIOError("Seeking to start of file failed"),
293                              "fseek", errno);
294     }
295
296     std::vector<char> data(len);
297     file.readBytes(&data[0], len);
298     file.close();
299
300     std::string result(&data[0], len);
301     // The below is necessary on Windows to make newlines stay as '\n' on a
302     // roundtrip.
303     result = replaceAll(result, "\r\n", "\n");
304
305     return result;
306 }
307
308 // static
309 std::string File::readToString(const std::string &filename)
310 {
311     return readToString(filename.c_str());
312 }
313
314 // static
315 void File::writeFileFromString(const std::string &filename,
316                                const std::string &text)
317 {
318     File file(filename, "w");
319     file.writeString(text);
320 }
321
322 } // namespace gmx