2 Copyright (C) 2013 Carl Hetherington <cth@carlh.net>
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 2 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #include "file_group.h"
23 #include "exceptions.h"
28 FileGroup::FileGroup (boost::filesystem::path p)
36 FileGroup::FileGroup (vector<boost::filesystem::path> const & p)
45 FileGroup::~FileGroup ()
48 fclose (_current_file);
53 /** Ensure that the given path index in the content is the _current_file */
55 FileGroup::ensure_open_path (size_t p) const
57 if (_current_file && _current_path == p) {
63 fclose (_current_file);
67 _current_file = fopen (_paths[_current_path].string().c_str(), "rb");
68 if (_current_file == 0) {
69 throw OpenFileError (_paths[_current_path]);
74 FileGroup::seek (int64_t pos, int whence) const
76 int64_t const len = length ();
78 /* Convert pos to `full_pos', which is an offset from the start
87 for (size_t i = 0; i < _current_path; ++i) {
88 full_pos += boost::filesystem::file_size (_paths[i]);
90 full_pos += ftell (_current_file);
98 /* Seek to full_pos */
100 int64_t sub_pos = full_pos;
101 while (i < _paths.size ()) {
102 boost::uintmax_t len = boost::filesystem::file_size (_paths[i]);
103 if (sub_pos < int64_t (len)) {
110 if (i == _paths.size ()) {
114 ensure_open_path (i);
115 fseek (_current_file, sub_pos, SEEK_SET);
119 /** Try to read some data from the current position into a buffer.
120 * @param buffer Buffer to write data into.
121 * @param amount Number of bytes to read.
122 * @return Number of bytes read, or -1 in the case of error.
125 FileGroup::read (uint8_t* buffer, int amount) const
129 int const this_time = fread (buffer + read, 1, amount - read, _current_file);
131 if (read == amount) {
136 /* See if there is another file to use */
137 if ((_current_path + 1) >= _paths.size()) {
140 ensure_open_path (_current_path + 1);
147 FileGroup::length () const
150 for (size_t i = 0; i < _paths.size(); ++i) {
151 len += boost::filesystem::file_size (_paths[i]);