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