Markup substitution through HelpWriterContext.
[alexxy/gromacs.git] / src / gromacs / utility / file.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013, 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.
8  *
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.
13  *
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.
18  *
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.
23  *
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.
31  *
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.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements gmx::File.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_utility
41  */
42 #include "file.h"
43
44 #include <cerrno>
45 #include <cstdio>
46 #include <cstring>
47
48 #include <algorithm>
49 #include <string>
50 #include <vector>
51
52 #include "gromacs/fileio/futil.h"
53
54 #include "gromacs/utility/exceptions.h"
55 #include "gromacs/utility/gmxassert.h"
56 #include "gromacs/utility/stringutil.h"
57
58 namespace gmx
59 {
60
61 /*! \internal \brief
62  * Private implementation class for File.
63  *
64  * \ingroup module_utility
65  */
66 class File::Impl
67 {
68     public:
69         /*! \brief
70          * Initialize a file object with the given handle.
71          *
72          * \param[in]  fp     %File handle to use (may be NULL).
73          * \param[in]  bClose Whether this object should close its file handle.
74          */
75         Impl(FILE *fp, bool bClose);
76         ~Impl();
77
78         //! File handle for this object (may be NULL).
79         FILE                   *fp_;
80         /*! \brief
81          * Whether \p fp_ should be closed by this object.
82          *
83          * Can be true if \p fp_ is NULL.
84          */
85         bool                    bClose_;
86 };
87
88 File::Impl::Impl(FILE *fp, bool bClose)
89     : fp_(fp), bClose_(bClose)
90 {
91 }
92
93 File::Impl::~Impl()
94 {
95     if (fp_ != NULL && bClose_)
96     {
97         if (fclose(fp_) != 0)
98         {
99             // TODO: Log the error somewhere
100         }
101     }
102 }
103
104 File::File(const char *filename, const char *mode)
105     : impl_(new Impl(NULL, true))
106 {
107     open(filename, mode);
108 }
109
110 File::File(const std::string &filename, const char *mode)
111     : impl_(new Impl(NULL, true))
112 {
113     open(filename, mode);
114 }
115
116 File::File(FILE *fp, bool bClose)
117     : impl_(new Impl(fp, bClose))
118 {
119 }
120
121 File::~File()
122 {
123 }
124
125 void File::open(const char *filename, const char *mode)
126 {
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)
132     {
133         GMX_THROW_WITH_ERRNO(
134                 FileIOError(formatString("Could not open file '%s'", filename)),
135                 "fopen", errno);
136     }
137 }
138
139 void File::open(const std::string &filename, const char *mode)
140 {
141     open(filename.c_str(), mode);
142 }
143
144 void File::close()
145 {
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);
151     impl_->fp_ = NULL;
152     if (!bOk)
153     {
154         GMX_THROW_WITH_ERRNO(
155                 FileIOError("Error while closing file"), "fclose", errno);
156     }
157 }
158
159 FILE *File::handle()
160 {
161     GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
162                        "Attempted to access a file object that is not open");
163     return impl_->fp_;
164 }
165
166 void File::readBytes(void *buffer, size_t bytes)
167 {
168     errno = 0;
169     FILE  *fp = handle();
170     // TODO: Retry based on errno or something else?
171     size_t bytesRead = std::fread(buffer, 1, bytes, fp);
172     if (bytesRead != bytes)
173     {
174         if (feof(fp))
175         {
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))));
182         }
183         else
184         {
185             GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
186                                  "fread", errno);
187         }
188     }
189 }
190
191 bool File::readLine(std::string *line)
192 {
193     if (!readLineWithTrailingSpace(line))
194     {
195         return false;
196     }
197     size_t endPos = line->find_last_not_of(" \t\r\n");
198     if (endPos != std::string::npos)
199     {
200         line->resize(endPos + 1);
201     }
202     return true;
203 }
204
205 bool File::readLineWithTrailingSpace(std::string *line)
206 {
207     line->clear();
208     const size_t bufsize = 256;
209     std::string  result;
210     char         buf[bufsize];
211     buf[0] = '\0';
212     FILE        *fp = handle();
213     while (fgets(buf, bufsize, fp) != NULL)
214     {
215         size_t length = std::strlen(buf);
216         result.append(buf, length);
217         if (length < bufsize - 1 || buf[length - 1] == '\n')
218         {
219             break;
220         }
221     }
222     if (ferror(fp))
223     {
224         GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
225                              "fgets", errno);
226     }
227     *line = result;
228     return !result.empty() || !feof(fp);
229 }
230
231 void File::writeString(const char *str)
232 {
233     if (fprintf(handle(), "%s", str) < 0)
234     {
235         GMX_THROW_WITH_ERRNO(FileIOError("Writing to file failed"),
236                              "fprintf", errno);
237     }
238 }
239
240 void File::writeLine(const char *line)
241 {
242     size_t length = std::strlen(line);
243
244     writeString(line);
245     if (length == 0 || line[length-1] != '\n')
246     {
247         writeString("\n");
248     }
249 }
250
251 void File::writeLine()
252 {
253     writeString("\n");
254 }
255
256 // static
257 bool File::exists(const char *filename)
258 {
259     return gmx_fexist(filename);
260 }
261
262 // static
263 bool File::exists(const std::string &filename)
264 {
265     return exists(filename.c_str());
266 }
267
268 // static
269 File &File::standardInput()
270 {
271     static File stdinObject(stdin, false);
272     return stdinObject;
273 }
274
275 // static
276 File &File::standardOutput()
277 {
278     static File stdoutObject(stdout, false);
279     return stdoutObject;
280 }
281
282 // static
283 File &File::standardError()
284 {
285     static File stderrObject(stderr, false);
286     return stderrObject;
287 }
288
289 // static
290 std::string File::readToString(const char *filename)
291 {
292     // Binary mode is required on Windows to be able to determine a size
293     // that can be passed to fread().
294     File  file(filename, "rb");
295     FILE *fp = file.handle();
296
297     if (std::fseek(fp, 0L, SEEK_END) != 0)
298     {
299         GMX_THROW_WITH_ERRNO(FileIOError("Seeking to end of file failed"),
300                              "fseek", errno);
301     }
302     long len = std::ftell(fp);
303     if (len == -1)
304     {
305         GMX_THROW_WITH_ERRNO(FileIOError("Reading file length failed"),
306                              "ftell", errno);
307     }
308     if (std::fseek(fp, 0L, SEEK_SET) != 0)
309     {
310         GMX_THROW_WITH_ERRNO(FileIOError("Seeking to start of file failed"),
311                              "fseek", errno);
312     }
313
314     std::vector<char> data(len);
315     file.readBytes(&data[0], len);
316     file.close();
317
318     std::string result(&data[0], len);
319     // The below is necessary on Windows to make newlines stay as '\n' on a
320     // roundtrip.
321     result = replaceAll(result, "\r\n", "\n");
322
323     return result;
324 }
325
326 // static
327 std::string File::readToString(const std::string &filename)
328 {
329     return readToString(filename.c_str());
330 }
331
332 // static
333 void File::writeFileFromString(const std::string &filename,
334                                const std::string &text)
335 {
336     File file(filename, "w");
337     file.writeString(text);
338 }
339
340 } // namespace gmx