Working with Streams 629
17
Binary Versus Text Files ......................................................................................
Some operating systems distinguish between text files and binary files. Text files store
everything as text (as you might have guessed), so large numbers such as 54,325 are
stored as a string of numerals (‘5’, ‘4’, ‘,’, ‘3’, ‘2’, ‘5’). This can be inefficient, but has
the advantage that the text can be read using simple programs such as the DOS and
Windows command-line program type.
To help the file system distinguish between text and binary files, C++ provides the
ios::binaryflag. On many systems, this flag is ignored because all data is stored in
binary format. On some rather prudish systems, the ios::binaryflag is illegal and does-
n’t even compile!
Binary files can store not only integers and strings, but also entire data structures. You
can write all the data at one time by using the write()method of fstream.
If you use write(), you can recover the data using read(). Each of these functions
expects a pointer to character, however, so you must cast the address of your class to be a
pointer to character.
The second argument to these functions is the number of characters expected to be read
or written, which you can determine using sizeof(). Note that what is being written is
the data, not the methods. What is recovered is only data. Listing 17.18 illustrates writing
the contents of an object to a file.
LISTING17.18 Writing a Class to a File
0: //Listing 17.18 Writing a Class to a File
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;