Improve MessageStringCollector
[alexxy/gromacs.git] / src / gromacs / utility / filestream.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2015,2017,2018,2019,2020, 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 classes from filestream.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_utility
41  */
42 #include "gmxpre.h"
43
44 #include "filestream.h"
45
46 #include "config.h"
47
48 #include <cerrno>
49 #include <cstdio>
50
51 #ifdef HAVE_UNISTD_H
52 #    include <unistd.h>
53 #endif
54
55 #include "gromacs/utility/exceptions.h"
56 #include "gromacs/utility/gmxassert.h"
57 #include "gromacs/utility/stringutil.h"
58
59 namespace gmx
60 {
61
62 namespace
63 {
64
65 //! Helper function for implementing readLine() for input streams.
66 bool readLineImpl(FILE* fp, std::string* line)
67 {
68     line->clear();
69     const size_t bufsize = 256;
70     std::string  result;
71     char         buf[bufsize];
72     buf[0] = '\0';
73     while (std::fgets(buf, bufsize, fp) != nullptr)
74     {
75         const size_t length = std::strlen(buf);
76         result.append(buf, length);
77         if (length < bufsize - 1 || buf[length - 1] == '\n')
78         {
79             break;
80         }
81     }
82     if (std::ferror(fp))
83     {
84         GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"), "fgets", errno);
85     }
86     *line = result;
87     return !result.empty() || (std::feof(fp) == 0);
88 }
89
90 } // namespace
91
92 namespace internal
93 {
94
95 /********************************************************************
96  * FileStreamImpl
97  */
98
99 class FileStreamImpl
100 {
101 public:
102     explicit FileStreamImpl(FILE* fp) : fp_(fp), bClose_(false) {}
103     FileStreamImpl(const char* filename, const char* mode) : fp_(nullptr), bClose_(true)
104     {
105         fp_ = std::fopen(filename, mode);
106         if (fp_ == nullptr)
107         {
108             GMX_THROW_WITH_ERRNO(
109                     FileIOError(formatString("Could not open file '%s'", filename)), "fopen", errno);
110         }
111     }
112     ~FileStreamImpl()
113     {
114         if (fp_ != nullptr && bClose_)
115         {
116             if (std::fclose(fp_) != 0)
117             {
118                 // TODO: Log the error somewhere
119             }
120         }
121     }
122
123     FILE* handle()
124     {
125         GMX_RELEASE_ASSERT(fp_ != nullptr, "Attempted to access a file object that is not open");
126         return fp_;
127     }
128
129     void close()
130     {
131         GMX_RELEASE_ASSERT(fp_ != nullptr, "Attempted to close a file object that is not open");
132         GMX_RELEASE_ASSERT(bClose_, "Attempted to close a file object that should not be");
133         const bool bOk = (std::fclose(fp_) == 0);
134         fp_            = nullptr;
135         if (!bOk)
136         {
137             GMX_THROW_WITH_ERRNO(FileIOError("Error while closing file"), "fclose", errno);
138         }
139     }
140
141 private:
142     //! File handle for this object (NULL if the stream has been closed).
143     FILE* fp_;
144     //! Whether \p fp_ should be closed by this object.
145     bool bClose_;
146 };
147
148 } // namespace internal
149
150 using internal::FileStreamImpl;
151
152 /********************************************************************
153  * StandardInputStream
154  */
155
156 // static
157 bool StandardInputStream::isInteractive()
158 {
159 #ifdef HAVE_UNISTD_H
160     return isatty(fileno(stdin)) != 0;
161 #else
162     return true;
163 #endif
164 }
165
166 bool StandardInputStream::readLine(std::string* line)
167 {
168     return readLineImpl(stdin, line);
169 }
170
171 /********************************************************************
172  * TextInputFile
173  */
174
175 // static
176 FilePtr TextInputFile::openRawHandle(const char* filename)
177 {
178     FilePtr fp(fopen(filename, "r"));
179     if (fp == nullptr)
180     {
181         GMX_THROW_WITH_ERRNO(
182                 FileIOError(formatString("Could not open file '%s'", filename)), "fopen", errno);
183     }
184     return fp;
185 }
186
187 // static
188 FilePtr TextInputFile::openRawHandle(const std::string& filename)
189 {
190     return openRawHandle(filename.c_str());
191 }
192
193 TextInputFile::TextInputFile(const std::string& filename) :
194     impl_(new FileStreamImpl(filename.c_str(), "r"))
195 {
196 }
197
198 TextInputFile::TextInputFile(FILE* fp) : impl_(new FileStreamImpl(fp)) {}
199
200 TextInputFile::~TextInputFile() {}
201
202 FILE* TextInputFile::handle()
203 {
204     return impl_->handle();
205 }
206
207 bool TextInputFile::readLine(std::string* line)
208 {
209     return readLineImpl(impl_->handle(), line);
210 }
211
212 void TextInputFile::close()
213 {
214     impl_->close();
215 }
216
217 /********************************************************************
218  * TextOutputFile
219  */
220
221 TextOutputFile::TextOutputFile(const std::string& filename) :
222     impl_(new FileStreamImpl(filename.c_str(), "w"))
223 {
224 }
225
226 TextOutputFile::TextOutputFile(FILE* fp) : impl_(new FileStreamImpl(fp)) {}
227
228 TextOutputFile::~TextOutputFile() {}
229
230 void TextOutputFile::write(const char* str)
231 {
232     if (std::fprintf(impl_->handle(), "%s", str) < 0)
233     {
234         GMX_THROW_WITH_ERRNO(FileIOError("Writing to file failed"), "fprintf", errno);
235     }
236 }
237
238 void TextOutputFile::close()
239 {
240     impl_->close();
241 }
242
243 // static
244 TextOutputFile& TextOutputFile::standardOutput()
245 {
246     static TextOutputFile stdoutObject(stdout);
247     return stdoutObject;
248 }
249
250 // static
251 TextOutputFile& TextOutputFile::standardError()
252 {
253     static TextOutputFile stderrObject(stderr);
254     return stderrObject;
255 }
256
257 } // namespace gmx