Pages

Sunday, November 6, 2011

Binary Files

In the earlier posts, I wrote about handling text or character files. Now is the time to learn another type of file handling - Binary File Handling.

 
What is a Binary File
All the files that we use are not text or char files. We don't "read" all the files, some of them are "heard" or "viewed"  also like audio, picture or video files. A char file is something that stores only char data that can be easily read using a basic text editor whereas a binary file can be a collection of text, char or audio, video etc.In binary files, to input and output data with the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...).
 
File streams include two member functions specifically designed to input and output binary data sequentially: write and read. The first one (write) is a member function of ostream inherited by ofstream. And read is a member function of istream that is inherited by ifstream. Objects of class fstream have both members. Their prototypes are:
 
write ( memory_block, size );
read ( memory_block, size );
 
 
Where memory_block is of type "pointer to char" (char*), and represents the address of an array of bytes where the read data elements are stored or from where the data elements to be written are taken. The size parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.
Binary files are very similar to arrays of structures, except the structures are in a disk-file rather than an array in memory. Binary files have two features that distinguish them from text files:
  1. You can instantly use any structure in the file.
  2. You can change the contents of a structure anywhere in the file.
Why Should I use Binary Files Handling Functions
The answer is quite simple - If you use the functions like put() or get() , you can only handle characters or strings since these functions only know how to handle chars. So if a user wishes to input an integer or float value, these function will show their incapability in processing the same. On the other hand using binary file handling functions, we can easily process data of any type, be it integer, float, char or string.

Binary File Handling Functions
To read or write data in binary form the following functions are used
  1. write : To write the data in a file in binary format
  2. read : To read the data from a file in binary format.

0 comments:

Post a Comment