Describes sequential file access using file streams. File streams provide simple and portable file handling techniques.
Files
File operations
When a program is terminated, the program data stored in main
memory is lost. To store data permanently, you need to write that data to a file
on an external storage medium.
File Operations
Single characters or character strings can be written to
text files just like they can be output on screen. However, it is common
practice to store records in files. A record contains data that forms a logical
unit, such as the human resource information for a person. A write operation stores a record in a file, that is, the
existing record in the file is updated or a new record is added. When you read a record, this record is taken from the file and copied
to the data structure of a program.
Objects can be put into permanent storage using similar
techniques. However, this normally involves more than just storing an object's
data. You also need to ensure that the object can be correctly reconstructed
when it is read, and this in turn involves storing type information and
references to other objects.
External mass storage media, such as hard disks, are normally
block-oriented—that is, data is transferred in blocks whose size is a multiple
of 512 bytes. Efficient and easy file management thus implies putting the data
you need to store into temporary storage in main memory, in a so-called file buffer.
File Positions
From the viewpoint of a C++ program, a file is simply a long
byte array. The structure of the file, using records for example, is entirely
the programmer's responsibility, allowing for a maximum degree of
flexibility.
Every character in a file occupies a byte position. The first byte
occupies position 0, the second byte position 1, and so on. The current file position is the position of the byte that will
be read or written next. Each byte that is transferred automatically increases
the current file position by 1.
In the case of sequential access, the data
is read or written byte by byte in a fixed order. The first read operation
starts at the beginning of the file. If you need access to some piece of
information in a file, you must read the file content from start to finish.
Write operations can create a new file, overwrite an existing file, or append
new data to an existing file.
Easy access to given data in a file implies being able to set
the current file position as required. This technique is known as random file access and will be discussed in one of the
following chapters.
0 Comments