1 // tu_file.cpp -- Ignacio CastaƱo, Thatcher Ulrich <tu@tulrich.com> 2003
3 // This source code has been donated to the Public Domain. Do
4 // whatever you want with it.
6 // A file class that can be customized with callbacks.
10 #include <boost/format.hpp>
14 #include "GnashFileUtilities.h"
19 //// Create a file from a standard file pointer.
20 tu_file::tu_file(FILE* fp
, bool autoclose
= false)
29 // Close this file when destroyed unless not requested.
30 if (_autoclose
) close();
34 // Return the number of bytes actually read. EOF or an error would
35 // cause that to not be equal to "bytes".
37 tu_file::read(void* dst
, std::streamsize bytes
)
40 return std::fread(dst
, 1, bytes
, _data
);
43 // Return the number of bytes actually written.
45 tu_file::write(const void* src
, std::streamsize bytes
)
48 return std::fwrite(src
, 1, bytes
, _data
);
52 tu_file::seek(std::streampos pos
)
54 // TODO: optimize this by caching total stream size ?
55 if (static_cast<size_t>(pos
) > size()) return false;
57 std::clearerr(_data
); // make sure EOF flag is cleared.
58 const int result
= std::fseek(_data
, pos
, SEEK_SET
);
63 assert (std::ftell(_data
) == pos
);
71 const int err
= std::fseek(_data
, 0, SEEK_END
);
73 boost::format fmt
= boost::format(
74 _("Error while seeking to end: %1%")) % strerror(errno
);
75 throw IOException(fmt
.str());
82 std::streampos ret
= std::ftell(_data
);
83 if (ret
< 0) throw IOException("Error getting stream position");
85 assert(static_cast<size_t>(ret
) <= size());
92 return std::feof(_data
);
98 if (!_data
) return true;
99 return std::ferror(_data
);
103 tu_file::size() const
108 if (fstat(fileno(_data
), &statbuf
) < 0)
110 log_error("Could not fstat file");
111 return static_cast<size_t>(-1);
113 return statbuf
.st_size
;
124 } // end namespace gnash
128 // indent-tabs-mode: t