Sams Teach Yourself C++ in 21 Days

(singke) #1
19: long DaysAlive;
20: };
21:
22: int main() // returns 1 on error
23: {
24: char fileName[80];
25:
26:
27: cout << “Please enter the file name: “;
28: cin >> fileName;
29: ofstream fout(fileName,ios::binary);
30: if (!fout)
31: {
32: cout << “Unable to open “ << fileName << “ for writing.\n”;
33: return(1);
34: }
35:
36: Animal Bear(50,100);
37: fout.write((char*) &Bear,sizeof Bear);
38:
39: fout.close();
40:
41: ifstream fin(fileName,ios::binary);
42: if (!fin)
43: {
44: cout << “Unable to open “ << fileName << “ for reading.\n”;
45: return(1);
46: }
47:
48: Animal BearTwo(1,1);
49:
50: cout << “BearTwo weight: “ << BearTwo.GetWeight() << endl;
51: cout << “BearTwo days: “ << BearTwo.GetDaysAlive() << endl;
52:
53: fin.read((char*) &BearTwo, sizeof BearTwo);
54:
55: cout << “BearTwo weight: “ << BearTwo.GetWeight() << endl;
56: cout << “BearTwo days: “ << BearTwo.GetDaysAlive() << endl;
57: fin.close();
58: return 0;
59: }

Please enter the file name: Animals
BearTwo weight: 1
BearTwo days: 1
BearTwo weight: 50
BearTwo days: 100

OUTPUT


630 Day 17


LISTING17.18 continued
Free download pdf