Move "loop" related tests in their own dir. This is just to break the ice... ideally...
[gnash.git] / libbase / tu_file.cpp
blobc28b2fd550d721966469e2b1e5ea9a722bc91a8b
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.
8 #include "tu_file.h"
10 #include <boost/format.hpp>
11 #include <cerrno>
12 #include <cstdio>
14 #include "GnashFileUtilities.h"
15 #include "log.h"
17 namespace gnash {
19 //// Create a file from a standard file pointer.
20 tu_file::tu_file(FILE* fp, bool autoclose = false)
22 _data(fp),
23 _autoclose(autoclose)
27 tu_file::~tu_file()
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".
36 std::streamsize
37 tu_file::read(void* dst, std::streamsize bytes)
39 assert(dst);
40 return std::fread(dst, 1, bytes, _data);
43 // Return the number of bytes actually written.
44 std::streamsize
45 tu_file::write(const void* src, std::streamsize bytes)
47 assert(src);
48 return std::fwrite(src, 1, bytes, _data);
51 bool
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);
59 if (result == EOF) {
60 return false;
63 assert (std::ftell(_data) == pos);
65 return true;
68 void
69 tu_file::go_to_end()
71 const int err = std::fseek(_data, 0, SEEK_END);
72 if (err == -1) {
73 boost::format fmt = boost::format(
74 _("Error while seeking to end: %1%")) % strerror(errno);
75 throw IOException(fmt.str());
79 std::streampos
80 tu_file::tell() const
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());
86 return ret;
89 bool
90 tu_file::eof() const
92 return std::feof(_data);
95 bool
96 tu_file::bad() const
98 if (!_data) return true;
99 return std::ferror(_data);
102 size_t
103 tu_file::size() const
105 assert(_data);
107 struct stat statbuf;
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;
117 void
118 tu_file::close()
120 assert(_data);
121 std::fclose(_data);
124 } // end namespace gnash
126 // Local Variables:
127 // mode: C++
128 // indent-tabs-mode: t
129 // End: