49: Animal BearTwo(1,1);
50:
51: cout << “BearTwo weight: “ << BearTwo.GetWeight() << endl;
52: cout << “BearTwo days: “ << BearTwo.GetDaysAlive() << endl;
53:
54: fin.read((char*) &BearTwo, sizeof BearTwo);
55:
56: cout << “BearTwo weight: “ << BearTwo.GetWeight() << endl;
57: cout << “BearTwo days: “ << BearTwo.GetDaysAlive() << endl;
58: fin.close();
59: return 0;
60: }
BearTwo weight: 1
BearTwo days: 1
BearTwo weight: 50
BearTwo days: 100
The declaration of the Animalclass is the same as in Listing 17.18. This time,
however, rather than prompting the user for the filename, command-line argu-
ments are used. On line 22,main()is declared to take two parameters: the count of the
command-line arguments and a pointer to the array of command-line argument strings.
On lines 24–28 the program ensures that the expected number of arguments (exactly
two) is received. If the user fails to supply a single filename, an error message is printed:
Usage TestProgram <filename>
Then, the program exits. Note that by using argv[0]rather than hard-coding a program
name, you can compile this program to have any name, and this usage statement works
automatically. You can even rename the executable after it was compiled and the usage
statement will still be correct!
On line 30, the program attempts to open the supplied filename for binary output. No
reason exists to copy the filename into a local temporary buffer. It can be used directly
by accessing argv[1].
This technique is repeated on line 42 when the same file is reopened for input, and it is
used in the error condition statements when the files cannot be opened, on lines 33 and 45.
Summary ..............................................................................................................
Today, streams were introduced, and the global objects coutand cinwere described.
The goal of the istreamand ostreamobjects is to encapsulate the work of writing to
device drivers and buffering input and output.
OUTPUT
634 Day 17
LISTING17.20 continued
ANALYSIS