Write() and Read() Functions – Pedagogy Zone

By
Last updated:

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.

infile.read((char*)&V,sizeof(V));
outfile.write((char*)&V,sizeout(V);

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
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
void main()
{
float h [4] = {1.5,2.5,3.5,4.5}
ofstream outfile;
outfile.open("binary");
outfile.write((char*)& h, sizeof (h));
outfile.close();
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++)
{
cout.setf(ios::showpoint);
cout<<setw(10)<<setprecision(2)
<<h[i];
}
infile.close();
}
Reading and Writing Class Object
//Reading and writing class objects
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
class inventory
{
char name[10];
int code;
float cost;
Public:
void readdata(void);
void writedata(void);
};
void inventory::readdata()
{
cin>>name>>code>>cost;}
void main()
{
inventory item[3];
fstream file;
file.open ("Stock.dat",ios::in;ious::out);
for(int i=0; i<3; i++)
{
item[i].readdata();
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();
}
file.close()
}
Read More Topics
Virtual base class
Pure virtual function
Class template with overloaded operation
Error handling during file operation

Santhakumar Raja

Hello The goal of this blog is to keep students informed about developments in the field of education. encourages pupils to improve as writers and readers.

For Feedback - techactive6@gmail.com

Leave a Comment