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