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