Chapter 15 Binary and Random Access Files C

Chapter 15 Binary and Random Access Files C++: LEARN BY DOING Todd Breedlove Troy Scevers Randal L. Albert

15. 1 Text Files Versus Binary Files – Comparison • Text files • Readable by humans • Translates information being written to the file into ASCII or Unicode characters • Binary files • Written in a way that requires no translation • Virtually unreadable by humans • Unusable for reports

15. 1 Text Files Versus Binary Files – Hex Dump • Program executables or documents created using Microsoft Word or other word processors are examples of binary files • Visual Studio actually shows a hex dump of binary files • hex dump • Shows contents of a binary file in hexadecimal format as well as a translation of those bytes recognizable as ASCII or Unicode characters

15. 1. 1 Advantages and Disadvantages of Binary Files • Advantages • No need to translate into ASCII characters • Allows special formatting symbols or commands to be placed within the file • Disadvantages • Not directly human readable • Not always portable from one machine to another

15. 2 Opening and Closing Binary Files – Syntax • Opening is similar as text files ifstream in. File ( filename, mode ); -- OR -ofstream out. File; out. File. open ( filename, mode );

15. 2 Opening and Closing Binary Files – Modes Mode ios: : in ios: : out ios: : app ios: : ate ios: : binary ios: : trunc Description Open file for input. Open file for output. All new output is added at the end of the file. Open file with the file pointer initially set at the end of the file. Data can be written anywhere within the file. Open file in binary mode (the default mode is text). Open file for output. If already exists, it is replaced by the new file. If using ios: : out this is the default unless you specify ios: : app, ios: : ate, or ios: : in.

15. 2 Opening and Closing Binary Files – Examples • When working with binary streams, include the second parameter ios: : binary ifstream input ( "filename. bin", ios: : binary ); ofstream fout; fout. open ( "filename. bin", ios: : out | ios: : binary ); ofstream data ( "c: \data. bin", ios: : out | ios: : app | ios: : binary ); • Multiple file mode flags can be combined using the bitwise OR operator (|) • The binary file in the third example is opened in append mode

15. 2 Opening and Closing Binary Files – Refresher • clear method clears, or resets, the I/O state flags for the stream • When end of a file (EOF) is reached a stream state flag of eofbit is set • Attempt to reuse a stream object requires clearing this flag • Once done with input and output activities always close the file • Syntax same as used when closing text files • Style note • Common when naming files to use extension of. bin as illustrated in our examples

15. 3 Binary File I/O – Syntax • Reading • Accomplished using an ifstream object stream. read ( char * buffer, streamsize ); • Writing • Accomplished using an ofstream object stream. write ( char * buffer, streamsize ); • First parameter • Information to be written, or buffer to store the information • Must be cast to a char * (i. e. , a character pointer) • Requires an address of a block of memory where every element is one byte long • Second parameter • Number of bytes to be read or written • If EOF marker is encountered before extracting the number of bytes specified, the read method will stop • The gcount member function is used to retrieve the number of bytes read during the last read
![15. 3 Binary File I/O – main Example struct EMP { char name[30]; // 15. 3 Binary File I/O – main Example struct EMP { char name[30]; //](http://slidetodoc.com/presentation_image_h2/395e5989682b7ecba816dc1bca5ddeed/image-10.jpg)
15. 3 Binary File I/O – main Example struct EMP { char name[30]; // Use c. String not dynamic short int age; }; const short int NUM_EMPLOYEES = 3; int main ( ) { EMP ray[NUM_EMPLOYEES]; Fill. Array. From. Keyboard ( ray ); Write. To. File ( ray ); Read. From. File ( ray ); Print. Array ( ray ); } return 0;

15. 3 Binary File I/O – Write. To. File Example void Write. To. File ( EMP ray[] ) { ofstream fout ( "binary. bin", ios: : out | ios: : binary ); if ( fout. is_open ( ) ) { fout. write ( reinterpret_cast <char *> (ray), sizeof ( EMP ) * NUM_EMPLOYEES ); fout. close ( ); } else cout << "File not opened" << endl; }

15. 3 Binary File I/O – Read. From. File Example void Read. From. File ( EMP ray[] ) { ifstream fin ( "binary. bin", ios: : in | ios: : binary ); if ( fin. is_open ( ) ) { fin. read ( reinterpret_cast <char *>(ray), sizeof ( EMP ) * NUM_EMPLOYEES ); cout << "Number of bytes read is: " << fin. gcount ( ); fin. close ( ); } else cout << "File not opened" << endl; }

15. 3 Binary File I/O – Explanation • The reinterpret_cast on the previous slide is another form of type casting usually used to convert an address to a different type of address • Discouraged by many programmers because it can be unsafe, it is a necessary evil in this case • Structure should contain only fixed size data members • Do not use pointers as data members until after the next section

15. 4 Record Serialization and Deserialization – Definition • Writing and reading the data that is a fixed size is relatively simple • With dynamic c. Strings it is not enough to write the data, it also must have information to be able to recreate the dynamic c. String • Serialization • The process of converting a record into a stream of bytes to store the data into a file • Its main purpose is to save the data in order to be able to recreate it when needed • Deserialization • Recreating the data from a stream of bytes

15. 4 Record Serialization and Deserialization – Process • Serialization • Write the number of characters in the dynamic c. String • Write the actual string data • Deserialization • Reads the number of characters in the c. String • Dynamically allocate memory of the correct size • Read the data from the binary file • It is also common practice to write the number of records as the first piece of data in the file

15. 4. 1 Serialization – Step 1 • Write the number of records to the file fout. write ( reinterpret_cast<char *>(&num_faculty), sizeof ( num_faculty ) ); • The figure below is a hex dump from Visual Studio • Highlighted is the data written in little-endian format

15. 4. 1 Serialization – Step 2 • Writing the number of characters in the dynamic c. String // Get length of name including '