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