Home » Learn C++ » The Write Function in C++

The Write Function in C++

The Write Function:

            The “write” function writes data or records into a data file in bytes. It writes an object consisting of a block of bytes into the data file. All types of data like struct, array, class object, graphics, etc. can he stored into the tile on the disk by this function. The general syntax of this function is:

object.write ((char*) & rec, sizeof(rec)) ;

 

Where

 

object: represents the created object of ofstream (or fstream).

 

write:  represents the member function of the created object.

char*: represents the data address of fixed length in bytes of the character type data.

rec:     represents a variable or object that contains data. It may be of any data type. In case of struct type and class object, the address operator (&) is added with it.

 

sizeof (rec): returns the size of the variable or object. The size of the object is calculated first in bytes and then the data is stored.

 

Program:

            Write a program to store records of employees on the disk in binary format.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <stdlib.h>
struct abc
{
char code[5] ,name[15], address[20];
int pay;

}
main ( )
{
abc rec;
char op;
ofstream addrec (“employee.dat”,ios : : binary);

if( laddrec)
{
cerr << “File opening error” <<endl;
exit (1) ;
}
do

{
clrscr ( );
cout << “Enter Code ?”;
cin >> rec.code;
cout << “Enter Name ?”;
cin >> rec .name;

cout << “Enter Address ?”;
cin >> rec.address;
cout << “Enter Pay ?”;
cin >> rec .pay;
addrec.write ((char*)&rec, sizeof (rec));
cout << “More Records [y/n] ?” ; cin >> op;
}whi1e (op== ‘y’ || op == ‘y’);
addrec.close ( );
}

 

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.