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