Fix File::readToString() on Windows.
[alexxy/gromacs.git] / src / gromacs / utility / file.cpp
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11  * Copyright (c) 2001-2009, The GROMACS development team,
12  * check out http://www.gromacs.org for more information.
13  *
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * If you want to redistribute modifications, please consider that
20  * scientific software is very special. Version control is crucial -
21  * bugs must be traceable. We will be happy to consider code for
22  * inclusion in the official distribution, but derived work must not
23  * be called official GROMACS. Details are found in the README & COPYING
24  * files - if they are missing, get the official version at www.gromacs.org.
25  *
26  * To help us fund GROMACS development, we humbly ask that you cite
27  * the papers on the package - you can find them in the top README file.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \internal \file
32  * \brief
33  * Implements gmx::File.
34  *
35  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
36  * \ingroup module_utility
37  */
38 #include "file.h"
39
40 #include <cerrno>
41 #include <cstdio>
42
43 #include <algorithm>
44 #include <string>
45 #include <vector>
46
47 #include "gromacs/utility/exceptions.h"
48 #include "gromacs/utility/gmxassert.h"
49 #include "gromacs/utility/format.h"
50
51 namespace gmx
52 {
53
54 File::File(const char *filename, const char *mode)
55     : fp_(NULL)
56 {
57     open(filename, mode);
58 }
59
60 File::File(const std::string &filename, const char *mode)
61     : fp_(NULL)
62 {
63     open(filename, mode);
64 }
65
66 File::~File()
67 {
68     if (fp_ != NULL)
69     {
70         if (fclose(fp_) != 0)
71         {
72             // TODO: Log the error somewhere
73         }
74     }
75 }
76
77 void File::open(const char *filename, const char *mode)
78 {
79     GMX_RELEASE_ASSERT(fp_ == NULL,
80                        "Attempted to open the same file object twice");
81     // TODO: Port all necessary functionality from ffopen() here.
82     fp_ = fopen(filename, mode);
83     if (fp_ == NULL)
84     {
85         GMX_THROW_WITH_ERRNO(
86                 FileIOError(formatString("Could not open file '%s'", filename)),
87                 "fopen", errno);
88     }
89 }
90
91 void File::open(const std::string &filename, const char *mode)
92 {
93     open(filename.c_str(), mode);
94 }
95
96 void File::close()
97 {
98     GMX_RELEASE_ASSERT(fp_ != NULL,
99                        "Attempted to close a file object that is not open");
100     bool bOk = (fclose(fp_) == 0);
101     fp_ = NULL;
102     if (!bOk)
103     {
104         GMX_THROW_WITH_ERRNO(
105                 FileIOError("Error while closing file"), "fclose", errno);
106     }
107 }
108
109 FILE *File::handle()
110 {
111     GMX_RELEASE_ASSERT(fp_ != NULL,
112                        "Attempted to access a file object that is not open");
113     return fp_;
114 }
115
116 void File::readBytes(void *buffer, size_t bytes)
117 {
118     GMX_RELEASE_ASSERT(fp_ != NULL,
119                        "Attempted to access a file object that is not open");
120     errno = 0;
121     // TODO: Retry based on errno or something else?
122     size_t bytesRead = std::fread(buffer, 1, bytes, fp_);
123     if (bytesRead != bytes)
124     {
125         if (feof(fp_))
126         {
127             GMX_THROW(FileIOError(
128                         formatString("Premature end of file\n"
129                                      "Attempted to read: %d bytes\n"
130                                      "Successfully read: %d bytes",
131                                      static_cast<int>(bytes),
132                                      static_cast<int>(bytesRead))));
133         }
134         else
135         {
136             GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
137                                  "fread", errno);
138         }
139     }
140 }
141
142 // static
143 std::string File::readToString(const char *filename)
144 {
145     // Binary mode is required on Windows to be able to determine a size
146     // that can be passed to fread().
147     File file(filename, "rb");
148     FILE *fp = file.handle();
149
150     if (std::fseek(fp, 0L, SEEK_END) != 0)
151     {
152         GMX_THROW_WITH_ERRNO(FileIOError("Seeking to end of file failed"),
153                              "fseek", errno);
154     }
155     long len = std::ftell(fp);
156     if (len == -1)
157     {
158         GMX_THROW_WITH_ERRNO(FileIOError("Reading file length failed"),
159                              "ftell", errno);
160     }
161     if (std::fseek(fp, 0L, SEEK_SET) != 0)
162     {
163         GMX_THROW_WITH_ERRNO(FileIOError("Seeking to start of file failed"),
164                              "fseek", errno);
165     }
166
167     std::vector<char> data(len);
168     file.readBytes(&data[0], len);
169     file.close();
170
171     std::string result(&data[0], len);
172     // The below is necessary on Windows to make newlines stay as '\n' on a
173     // roundtrip.  Perhaps would be better to only replace '\r\n' with '\n',
174     // but in practice this probably makes little difference.
175     std::string::iterator end = std::remove(result.begin(), result.end(), '\r');
176     result.erase(end, result.end());
177
178     return result;
179 }
180
181 // static
182 std::string File::readToString(const std::string &filename)
183 {
184     return readToString(filename.c_str());
185 }
186
187 } // namespace gmx