Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Streams 633

17


LISTING17.20 Using Command-line Arguments To Get a Filename


0: //Listing 17.20 Using Command-line Arguments
1: #include <fstream>
2: #include <iostream>
3: using namespace std;
4:
5: class Animal
6: {
7: public:
8: Animal(int weight,long days):itsWeight(weight),DaysAlive(days){}
9: ~Animal(){}
10:
11: int GetWeight()const { return itsWeight; }
12: void SetWeight(int weight) { itsWeight = weight; }
13:
14: long GetDaysAlive()const { return DaysAlive; }
15: void SetDaysAlive(long days) { DaysAlive = days; }
16:
17: private:
18: int itsWeight;
19: long DaysAlive;
20: };
21:
22: int main(int argc, char *argv[]) // returns 1 on error
23: {
24: if (argc != 2)
25: {
26: cout << “Usage: “ << argv[0] << “ <filename>” << endl;
27: return(1);
28: }
29:
30: ofstream fout(argv[1],ios::binary);
31: if (!fout)
32: {
33: cout << “Unable to open “ << argv[1] << “ for writing.\n”;
34: return(1);
35: }
36:
37: Animal Bear(50,100);
38: fout.write((char*) &Bear,sizeof Bear);
39:
40: fout.close();
41:
42: ifstream fin(argv[1],ios::binary);
43: if (!fin)
44: {
45: cout << “Unable to open “ << argv[1] << “ for reading.\n”;
46: return(1);
47: }
48:
Free download pdf