Does anyone know why the following code for writing
class data to a file does not work? Is there something
wrong with the way the book wrote the code???
-Book example prog for writing/reading from binary
file
-------------------------------------------------------
#include <fstream.h>
#include <stdlib.h>
class Animal
{
public:
Animal(int weight, long
days):itsWeight(weight),itsNumberDaysAlive(days){}
~Animal(){}
int GetWeight()const { return itsWeight; }
void SetWeight(int weight) { itsWeight = weight; }
long GetDaysAlive()const { return
itsNumberDaysAlive; }
void SetDaysAlive(long days) { itsNumberDaysAlive =
days; }
private:
int itsWeight;
long itsNumberDaysAlive;
};
int main(int argc, char *argv[]) // returns 1 on
error
{
if (argc != 2)
{
cout << "Usage: " << argv[0] << " <filename>" <<
endl;
return(1);
}
ofstream fout(argv[1],ios::binary);
if (!fout.good())
{
cout << "Unable to open " << argv[1] << " for
writing.\n";
return(1);
}
Animal Bear(50,100);
fout.write((char *)&Bear,sizeof(Bear));
fout.close();
ifstream fin(argv[1],ios::binary);
if (!fin.good())
{
cout << "Unable to open " << argv[1] << " for
reading.\n";
return(1);
}
Animal BearTwo(1,1);
cout << "BearTwo weight: " << BearTwo.GetWeight() <<
endl;
cout << "BearTwo days: " << BearTwo.GetDaysAlive() <<
endl;
fin.read((char *)&BearTwo, sizeof(BearTwo));
cout << "BearTwo weight: " << BearTwo.GetWeight() <<
endl;
cout << "BearTwo days: " << BearTwo.GetDaysAlive() <<
endl;
fin.close();
system("PAUSE");
return 0;
}
------------------------------------------------------
I would appreciate any help, I would like to get this
working so I can use it in one of my programs....
=====
Julio
__________________________________________________
Do You Yahoo!?
Buy the perfect holiday gifts at Yahoo! Shopping.
http://shopping.yahoo.com
|