Matthias said:
Thomas Matthews wrote:
Tanks for your reply. I thought about using a separate class for I/O too.
The most important point for me in your explanation is the use of unsigned
char to hold the data. Mind you asking me whats the advantage of using
unsigned over signed char? Do you agree to using std::ifstream::read() for
reading the data?
Unsigned char allows usage of all the bits, without any worries about
overflow and signing. I just want a simple 'byte' or smallest
accessible unit. The 'signed' quantities have issues when it comes
to bitmanipulation (such as shifting).
I guess it's just my style. You can find good discussions about
signed and unsigned integral types in this newsgroup and
our neighbor
You can use ifstream::read() as long as the file is opened in
binary mode. The binary mode tells the compiler/platform to
_NOT_ perform any translations on the data.
There are also claims that fread() is simpler and faster.
However, since developer time and quality is more important
than speed, go with ifstream::read().
In my Binary_Stream class, I have a pure virtual function:
unsigned long size_on_stream() const = 0;
All classes that use the Binary_Stream interface must provide
the size that they occupy on the stream. This allows one to
query an object about the size of data it requires in order
to allocate a buffer for reading:
unsigned long buffer_size = my_msg.size_on_stream();
unsigned char * buffer = new unsigned char[buffer_size];
my_data_file.read(buffer, buffer_size);
unsigned char * buf_ptr(buffer);
my_msg.load_from_buffer(buf_ptr);
delete [] buffer;
One nice benefit is that objects can be written to and read
from a stream without knowing any details about the object!
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book