1 | // SuperTux |
2 | // Copyright (C) 2006 Matthias Braun <matze@braunis.de> |
3 | // |
4 | // This program is free software: you can redistribute it and/or modify |
5 | // it under the terms of the GNU General Public License as published by |
6 | // the Free Software Foundation, either version 3 of the License, or |
7 | // (at your option) any later version. |
8 | // |
9 | // This program is distributed in the hope that it will be useful, |
10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
12 | // GNU General Public License for more details. |
13 | // |
14 | // You should have received a copy of the GNU General Public License |
15 | // along with this program. If not, see <http://www.gnu.org/licenses/>. |
16 | |
17 | #include "physfs/ofile_streambuf.hpp" |
18 | |
19 | #include <physfs.h> |
20 | #include <sstream> |
21 | #include <stdexcept> |
22 | |
23 | OFileStreambuf::OFileStreambuf(const std::string& filename) : |
24 | file() |
25 | { |
26 | file = PHYSFS_openWrite(filename.c_str()); |
27 | if (file == nullptr) { |
28 | std::stringstream msg; |
29 | msg << "Couldn't open file '" << filename << "': " |
30 | << PHYSFS_getLastErrorCode(); |
31 | throw std::runtime_error(msg.str()); |
32 | } |
33 | |
34 | setp(buf, buf+sizeof(buf)); |
35 | } |
36 | |
37 | OFileStreambuf::~OFileStreambuf() |
38 | { |
39 | sync(); |
40 | PHYSFS_close(file); |
41 | } |
42 | |
43 | int |
44 | OFileStreambuf::overflow(int c) |
45 | { |
46 | char c2 = static_cast<char>(c); |
47 | |
48 | if (pbase() == pptr()) |
49 | return 0; |
50 | |
51 | size_t size = pptr() - pbase(); |
52 | PHYSFS_sint64 res = PHYSFS_writeBytes(file, pbase(), size); |
53 | if (res <= 0) |
54 | return traits_type::eof(); |
55 | |
56 | if (c != traits_type::eof()) { |
57 | PHYSFS_sint64 res_ = PHYSFS_writeBytes(file, &c2, 1); |
58 | if (res_ <= 0) |
59 | return traits_type::eof(); |
60 | } |
61 | |
62 | setp(buf, buf + res); |
63 | return 0; |
64 | } |
65 | |
66 | int |
67 | OFileStreambuf::sync() |
68 | { |
69 | return overflow(traits_type::eof()); |
70 | } |
71 | |
72 | /* EOF */ |
73 | |