3 * PHP-Gettext External Library: StreamReader classes
6 * @subpackage PHP-gettext
9 Copyright (c) 2003, 2005 Danilo Segan <danilo@kvota.net>.
11 This file is part of PHP-gettext.
13 PHP-gettext is free software; you can redistribute it and/or modify
14 it under the terms of the GNU General Public License as published by
15 the Free Software Foundation; either version 2 of the License, or
16 (at your option) any later version.
18 PHP-gettext is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
23 You should have received a copy of the GNU General Public License
24 along with PHP-gettext; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30 // Simple class to wrap file streams, string streams, etc.
31 // seek is essential, and it should be byte stream
33 // should return a string [FIXME: perhaps return array of bytes?]
34 function read($bytes) {
38 // should return new position
39 function seekto($position) {
43 // returns current position
44 function currentpos() {
48 // returns length of entire stream (limit for seekto()s)
58 function StringReader($str='') {
63 function read($bytes) {
64 $data = substr($this->_str, $this->_pos, $bytes);
65 $this->_pos += $bytes;
66 if (strlen($this->_str)<$this->_pos)
67 $this->_pos = strlen($this->_str);
72 function seekto($pos) {
74 if (strlen($this->_str)<$this->_pos)
75 $this->_pos = strlen($this->_str);
79 function currentpos() {
84 return strlen($this->_str);
95 function FileReader($filename) {
96 if (file_exists($filename)) {
98 $this->_length=filesize($filename);
100 $this->_fd = fopen($filename,'rb');
102 $this->error = 3; // Cannot read file, probably permissions
106 $this->error = 2; // File doesn't exist
111 function read($bytes) {
113 fseek($this->_fd, $this->_pos);
115 // PHP 5.1.1 does not read more than 8192 bytes in one fread()
116 // the discussions at PHP Bugs suggest it's the intended behaviour
118 $chunk = fread($this->_fd, $bytes);
120 $bytes -= strlen($chunk);
122 $this->_pos = ftell($this->_fd);
128 function seekto($pos) {
129 fseek($this->_fd, $pos);
130 $this->_pos = ftell($this->_fd);
134 function currentpos() {
139 return $this->_length;
148 // Preloads entire file in memory first, then creates a StringReader
149 // over it (it assumes knowledge of StringReader internals)
150 class CachedFileReader extends StringReader {
151 function CachedFileReader($filename) {
152 if (file_exists($filename)) {
154 $length=filesize($filename);
155 $fd = fopen($filename,'rb');
158 $this->error = 3; // Cannot read file, probably permissions
161 $this->_str = fread($fd, $length);
165 $this->error = 2; // File doesn't exist