Write() and Read() Functions – theteche.com

These functions handles the data in binary from. This means that the values are stored in the desk file in the same format in which they are stored in the internal memory.

Write and read functions

The binary format is more accurate for storing numbers as they are stored in the exact internal representation. There are no conversions while saving he data and therefore saving is much faster.


First argument ⇒ is the address of the variable V
Second argument ⇒ length of that variable in bytes.

The address of the variable must be cast to type Char* (Pointer to Character type).

//Input/Output operations on binary files
void main()
float h [4] = {1.5,2.5,3.5,4.5}
ofstream outfile;
outfile.write((char*)& h, sizeof (h));
for (int i = 0; i<4; i++)
h[i] = 0;
ifstream infile;
infile.open ("binary")
infile.read ((char*) & h, sizeof (h));
for (i=0; i<4; i++)
Reading and Writing Class Object
//Reading and writing class objects
class inventory
char name[10];
int code;
float cost;
void readdata(void);
void writedata(void);
void inventory::readdata()
void main()
inventory item[3];
fstream file;
file.open ("Stock.dat",ios::in;ious::out);
for(int i=0; i<3; i++)
file.write ((char*)& item [i],sizeof [i]));
file.seekg (0);
for (i=0; i<3; i++)
file.read ((char*)&item [i], sizeof (item[i]));
item [i].writedata();

About the author

Santhakumar Raja

Hi, This blog is dedicated to students to stay update in the education industry. Motivates students to become better readers and writers.

View all posts

Leave a Reply