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