(BICS 265 Notes.13)
|
|
| Objects make it easier to write C++ programs. You've been using two pre-defined objects to simplify console (screen and keyboard) I/O since the beginning of the course:
Sending a stream of characters to disk is a more specific type of stream output. And reading a stream of characters from disk is a more specific type of stream input.
"If you're thinking in an object-oriented way, this should ring a bell..."
To simplify disk I/O, two additional classes are provided:
"There are no pre-defined ofstream or ifstream objects.
Because ofstream and ifstream are derived from classes you have been using throughout the course for console I/O, learning disk I/O is fairly easy.
Let's look at the steps involved in creating a disk file... |
Creating a Disk File(with examples)
|
|
| In the above example, default values were used when the file was
opened. By default, the file will be text mode - data that is int or float will be translated to ASCII text format when written to disk. Text mode files can be processed by virtually all types of microcomputers and operating systems. They can also be created, viewed, and edited with any text editor (such as Notepad, Microsoft Word, or the Visual C++ Editor).
Another default value used during open causes an existing file with the same name to be replaced.
"This could be dangerous..."
To override this default, code a second parameter when calling the open( ) function...
DiskOut.open("a:Myfile.dat",ios::noreplace);
If a file with the same name exists, the open will fail.
There are several other ios flags that may be specified when opening a file. Some of the common ones are as follows:
These flags can be used in combination by coding the bitwise OR operator (a single pipe) between them. For example,
DiskOut.open("a:Myfile.dat", ios::app | ios::binary);
Let's look at the steps involved in reading data from an existing disk file... |
Reading Data from an Existing Disk File(with examples)
|
|
| When reading data from a disk file, there is always the
possibility that no more data exists in the file. To test for this end-of-file condition, you may use the eof( ) member function. It returns a non-zero (TRUE) value if no more data exists in the file.
Example (Testing for end of file)
|
** There is no programming exercise for this lesson **