carnie wrote:
I have a BookData data structure that I'm trying to set up for file io. I
open a file for random access io (same file for input and output), and
write and read to the file with the following code.
BookData book;
long pos;
getBook(&book);
fstream data_file("books.dat",ios::in|ios::out);
pos = LookUpBook(book) - sizeof(book);
data_file.write((char *)&book,sizeof(book));
The problem is that no changes I make to the variable book are reflected in
the file. I'm using gcc 3.2.3 on a gentoo linux platform wit Reiser fs, if
that makes any difference. Any and all help is appreciated.
carnie :-)
One more issue: the size of a structure may not be sum of
the size of its members. The compiler is allowed to add padding
bytes between members and perhaps some bookkeeping data at the
end of the structure (or class).
I suggest only using the write() for POD types. Otherwise, have
members that write the structure to a stream:
class Book
{
string title;
string author;
string publisher;
string isbn;
public:
ostream& binary_write(ostream& out) const;
};
ostream&
Book ::
binary_write(ostream& out)
{
unsigned int length;
length = title.size();
out.write((unsigned char *) &length, sizeof(length));
out.write(title.c_str(), length);
length = author.size();
out.write((unsigned char *) &length, sizeof(length));
out.write(author.c_str(), length);
// etc.
return out;
}
In addition, I suggest a binary read method as well.
I've found that writing to buffers is more efficient
since it only uses one write for the entire buffer.
This requires more code though.
--
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
http://www.sgi.com/tech/stl -- Standard Template Library