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

The Read Function in C++

The Read Function:

            The “read” function is used to read data or records from the data file into the memory as blocks of bytes. The general syntax of this function is:

object.read ((char*)&rec, sizeof(rec));
 
 where

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

 
read: represents the member function of the created object.

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

 
rec: represents variable or object to store record or data. It must he of same type and size in which data was written in data file by using “write” function. In case of struct type and class object, the address operator (&) is added with it.

 
sizeof (rec): returns size of variable. The size of the object is calculated first and then the data is read.

 

Program:

            Write a program to read records back stored in the last tutorial program.

#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;
ifstream rrr( “emp1oyee.dat” ,ios : : binary);
clrscr ( );
if (!rrr)
{
cerr << “Fi1e opening error” <<endl;
exit (1)
while( !rrr.eof ( ))
{
rrr.read ((char*)&rec,sizeof(rec));
cout << rec.code << “\t “ <<rec.name << “\t << rec.address << “\t”<< rec.pay << endl;
}
rrr.close ( );
}

 

Other Topics

    comment closed

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