0% found this document useful (0 votes)
169 views

Data Files

The document provides information on file handling in C++. It discusses: - Streams are used to transfer data between memory and files/devices. Common streams include cin, cout, and file streams like ifstream and ofstream. - File streams like ifstream and ofstream associate an input or output stream with a file. They allow reading data from and writing data to files. - The fstream header provides file stream classes that inherit from iostream streams and support reading and writing files. Functions like open() and constructors can be used to associate streams with files. - Input and output functions like get() and put() are used to transfer individual characters or data types between memory and files

Uploaded by

Sai Charan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
169 views

Data Files

The document provides information on file handling in C++. It discusses: - Streams are used to transfer data between memory and files/devices. Common streams include cin, cout, and file streams like ifstream and ofstream. - File streams like ifstream and ofstream associate an input or output stream with a file. They allow reading data from and writing data to files. - The fstream header provides file stream classes that inherit from iostream streams and support reading and writing files. Functions like open() and constructors can be used to associate streams with files. - Input and output functions like get() and put() are used to transfer individual characters or data types between memory and files

Uploaded by

Sai Charan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

TOPIC : FILE HANDLING IN C++

INTRODUCTION
- IN COMPUTER THE PROCESSING TAKES PLACE BY HAVING INPUTS
FROM THE INPUT DEVICES AND AFTER PROCESSING SENDING THE
OUTPUT TO THE OUTPUT DEVICES. WHILE THE PROCESSING IS
TAKING PLACE AND ALSO WHEN THE PROCESSING IS OVER, THE
MEMORY IS USED FOR STORING ALL THE DATA OF THE SPECIFIED
TYPE. IN THIS KIND OF OUPUT THE STORAGE OF DATA IS NOT
PERMANENT. WHEN THE COMPUTER IS SWITCHED OFF THE DATA IN
MEMORY ALSO GETS ERASED OFF.
- THE FILES IN C++ ALLOWS TO STORE THE DATA PERMANENTLY SO
THAT THE PREVIOUSLY ENTERED DATA IS AVAILABLE TO THE
PROGRAM.
- A FILE IS A COLLECTION OF BYTES STORED ON SOME STORAGE
DEVICE LIKE DISK.

STREAMS
- A STREAM IS A SEQUENCE OF BYTES.
- IN C++ DATA FLOWS FROM THE SOURCE TO THE SINK
(DESTINATION).
- THE FLOW OF DATA FROM SOURCE TO DESTINATION ( SINK) IS
CALLED A STREAM.
- cin AND cout USED FOR INPUT AND OUTPUT ARE ALSO KNOWN AS
STEAMS.
- IN STREAM cin DATA FLOWS FROM THE KEYBOARD TO THE RAM.
- IN STREAM cout DATA FLOWS FROM THE RAM TO THE MONITOR. –
- STREAM cin IS THE MEMBER OF CLASS istream. STREAM cout IS THE
MEMBER OF CLASS ostream.THESE CLASSES ARE DECLARED IN
HEADER FILE iostream.h. OBJECTS cin AND cout HAVE ALSO BEEN
DECLARED IN THE SAME FILE. AS OBJECTS cin AND cout HAVE
ALREADY BEEN DECLARED, YOU CAN USE THEM ONLY BY
INCLUDING HEADER FILE iostream.h IN THE PROGRAM
- THE OPERATION OF WRITING THE DATA TO FILE INVOLVES FLOW
OF DATA FROM THE RAM TO THE FILE AND THE OPERATION OF
READING THE DATA FROM THE FILE INVOLVE FLOW OF DATA FROM
THE FILE TO THE RAM.

WRITE OPRATION TO THE FILE


DATA
OUTPUT WRITE DATA DISK
PROGR STREAM TO FILE FILE
AM
READING OPERATION FROM THE FILE

READ INPUT
DATA STREAM DATA
DISK
FILE PRGRAM

- THESE OPERATIONS REQUIRE C++ STREAMS WHICH ARE NOT


STANDARD C++ STREAMS. THESE STREAMS SHOULD BE THE OBJECTS
OF C++ CLASSES WHICH SUPPORT INPUT/OUTPUT. THE CLASSES
DESIGNED TO MANAGE THE DISK FILES ARE DECLARED IN fstream.h
THEREFORE THIS FILE SHOULD BE INCLUDED IN THE PROGRAMS OF
FILES. THE CLASSES DEFINED INSIDE fstream.h DERIVE FROM CLASSES
UNDER iostream.h, THE HEADER FILE THAT MANGAES I/O OPERATIONS.
- IN C++, A FILE AT IT’S LOWEST LEVEL IS INTERPRETED SIMPLY AS A
SEQUENCE OF OR STREAM OF BYTES. THE FILEI/O LIBRARY
MANAGES THE TRANSFER OF THESE BYTES. AT THIS LEVEL THE
NOTION OF A DATA TYPE IS NOT THERE.
- ON THE OTHER HAND, FILE AT THE USER LEVEL CONSIST OF A
SEQUENCE OF POSSIBLY INTERMIXED DATA TYPES: char ,int , float,
classes’ objects. HERE THE FILE I/O LIBRARY MANAGES THE
INTERFACE BETWEEN THESE TWO LEVELS.
-
STREAM CLASS HIERARCHY

ios

istream streambuf ostream

iostream

ifstream fstream ofstream filebuf

fstreambase

ASSOCIATING A STREAM WITH A FILE


- A FILE IS DEFINED BY A PHYSICAL NAME (WHICH APPEARS IN THE
DIRECTORY) AND LOGICAL NAME (WHICH IS ACTUALLY THE
OBJECT OF CLASS FSTREAM).
- DATA CAN BE READ OR WRITTEN TO A FILE ONLY IF THE CORRECT
NAME IS SUPPLIED TO THE OBJECTS OF THE CLASSES ifstream FOR
READING DATA AND ofstream FOR WRITING THE DATA.
- THERE ARE TWO WAYS OF LINKING STREAMS TO THE FILES:
A. BY USING CONSTRUCTORS OF THE STREAM CLASS
B. BY USING open() FUNCTION.
FILE OPENING THROUGH CONSTRUCORS OF STREAM CLASS
- CLASSES ifstream, ofstream AND fstream HAVE CONSTRUCTOR
FUNCTIONS WHICH OPEN FILES WHEN OBJECTS OF THESE CLASSES
ARE CREATED.
- WHEN AN OBJECT IS DECLARED WITH THE FILE NAME AS
ARGUMENT, THE CONSTRUCTOR FUNCTION OPENS FILE IN
APPROPRIATE MODE .
SYNTAX:
streamname objectname(“filename”);
EXAMPLE:
ifstream FF(“STUD.DAT”);
- WILL OPEN FILE STUD.DAT WITH OBJECT NAME (LOGICAL NAME) AS
FF IN IFSTREAM FOR READING PURPOSE.
ofstream STUD(“MARKS.DAT”);
- WILL OPEN FILE MARKS.DAT WITH OBJECT NAME AS STUD IN ofstream
FOR WRITING PURPOSE.
FILE OPENING USING open() FUNCTION.
- FUNCITON open() OPENS FILE FOR INPUT/OUTPUT OPERARTIONS.
SYNTAX
streamobject.open(“filename”);
EXAMPLE
ifstream fin;
fin.open(“stud.dat”);
- WILL OPEN STUD.DAT IN ifstream FOR READING PURPOSE.
ofstream fout;
fout.open(“stud.dat”);
- WILL OPEN STUD.DAT IN ofstream FOR WRITING PURPOSE.

Ios TAGS FOR SELECTING FILE MODES

ios TAG MEANING

ios::in open for reading


ios::out open for writing
ios::ate seeks for end of file upon opening
ios::app open for appending
ios::trunc truncates file if already exists
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file exists
ios::binary opens in binary mode

CHECKING FOR SUCCESSFUL FILE OPENING


- EVERY TIME A FILE IS OPENED FOR USING IN THE PROGRAM IT
SHOULD BE CHECKED FOR SUCCESSFUL OPERATION OF FILE
OPENING. THE PROGRAM SHOULD CONTINUE IF ONLY THE FILE HAS
BEEN OPENED SUCCESSFULLY.
EXAMPLE:
ifstream marks(“marks.dat”);
if(marks==NULL)
{
cout<<”\n unable to the file”
exit(1);
}
CLOSING OF FILE
- WHEN PROGRAM COMES TO AN END ALL OPEN FILES ARE
AUTOMATICALLY CLOSED. BUT IF HOWEVER ONE WISHES TO CLOSE
THE FILE IN THE PROGRAM , FILE CAN ALSO BE CLOSED.
SYNTAX:
streamname.close();
EXAMPLE:
marks.close();
TEXTFILE/BINARYFILE
- In BINARY FILE DATA IS STORED IN THE RAM. NUMERIC DATA NEEDS TO
BE TRANSLATED INTO CHARACTER STRING BEFORE IT CAN BE VIEWED ON
THE SCREEN . THEREORE, CONTENTS OF A BINARY FILE CAN NOT BE SEEN
THROUGH DOS TYPE COMMAND.
- IN TEXT FILES DATA OF NUMERIC AND OTHER TYPE IS STORED IN THE
CHARACTER STRING FORM, SO IT CAN BE SEEN THROUGH DOS TYPE
COMMAND.

WRITEING TO TEXTFILE
- OFSTREAM IS USED FOR OPENING THE FILE FOR WRITING PURPOSE.

PROGRAM:
//example of writing to a text file using the constructor to stream class
#include<fstream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int ch;
ofstream fout("chars.dat");
if(fout==NULL)
{
cout<<"\nerror in opening file";
exit(1);
}
for(ch='A';ch<='Z';ch++)
{
fout<<ch<<" ";
}
fout<<endl;
fout.close();
}

PROGRAM
// example of writing to a text file using the open() function
#include<fstream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int ch;
ofstream fout;
fout.open("chars.dat");
if(fout==NULL)
{
cout<<"\nerror in opening file";
exit(1);
}
for(ch='A';ch<='Z';ch++)
{
fout<<ch<<" ";
}
fout<<endl;
fout.close();
}

//program to input the roll number and marks of a set of students and
//store the data in the file
#include<fstream.h>
#include<conio.h>
#include<iomanip.h>
ofstream fout("result.dat");
class student
{
private:
int rollno,marks;
public:
void getdata()
{
cout<<"\n enter roll number";
cin>>rollno;
cout<<"\n enter marks";
cin>>marks;
}
void tofile()
{
fout<<setw(10)<<rollno<<setw(10)<<marks<<endl;
}
};
void main()
{
int i,n;
student stud;
clrscr();
cout<<"\nenter number of students";
cin>>n;
fout<<setw(10)<<"rollno"<<setw(10)<<"marks"<<endl;
for(i=0;i<n;i++)
{
stud.getdata();
stud.tofile();
}
fout.close();
}

READING FROM TEXTFILE


- IFSTREAM IS USED FOR OPENING THE FILE FOR READING PURPOSE
PRORGRAM.

//program to read an array from a file and display the same


#include<fstream.h>
#include<conio.h>
#include<iomanip.h>
#include<stdlib.h>
#include<stdio.h>
#define size 2
class array
{
private:
int n;
int x[size];
public:
void createfile();
void getarray();
void showarray();
};
void array :: createfile()
{
ofstream fout("num.dat");
for(int i=0;i<size;i++)
{
cout<<"\n enter number in the file";
cin>>n;
fout<<n;
}
fout.close();
}
void array :: getarray()
{
int i=0;
char fname[15];
cout<<"\n enter name of the file";
gets(fname);
ifstream fin(fname);
if(fin==NULL)
{
cout<<"\nerror in file opening";
exit(1);
}
while(!fin.eof())
{
fin>>x[i];
i++;
}
n=i-1;
}
void array :: showarray()
{
int i;
cout<<"\nthe array is";
for(i=0;i<n;i++)
cout<<setw(5)<<x[i];
cout<<endl;
}
void main()
{
array a;
clrscr();
a.createfile();
a.getarray();
a.showarray();
}

DETECTING END OF FILE(EOF)


- FUNCTION eof() USED FOR FINDING WHETHER ENDOF OF FILE HAS
OCCURRED OR NOT.
- Eof() FUNCTION RETURNS NONZERO NUMBER IF THE FILE HAS COME
TO AN END AND ZERO OTHERWISE.

INPUT FUNCTIONS
GET()
- FUNCTION GET() READS A SINGLE CHARACTER FROM AN INPUT
STREAM.
PROGRAM.
//program to copy a source file to destination file
#include<fstream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
char infile[5];
char outfile[5];
char ch;
clrscr();
while(!fin.eof())
{
ch=fin.get();
fout<<ch;
} ofstream fout("afile");
for(int i=0;i<10;i++)
{
cout<<"\n enter char in the file";
cin>>ch;
fout<<ch;
}
fout.close();
ifstream fin("afile");
if(!fin)
{
cout<<"\n error opening file";
exit(1);
}
ofstream fou("bfile");
while(!fin.eof())
{
ch=fin.get();
fou<<ch;
}
fin.close();
fou.close();
cout<<"\n copied data in new file";
ifstream fi("bfile");
while(!fi.eof())
{
ch=fi.get();
cout<<ch;
}
fi.close();
}

GETLINE()
- THE EXTRACTION OPERATOR (>>) IS OVERLOADED TO READ ANY
VARIABLE, CHARACTER, INTEGER,FLOAT OR DOUBLE.
- IT CAN READ A CHARACTER STRING ONLY IF THERE IS NO BLANK
SPACE IN IT. BECAUSE OPERATOR(>>) TAKES BLANK SPACE AS THE
DELIMITER WHICH SEPARATES TWO VARIABLES.
PROGRAM
//program to read line of text from the keyboard and
// write the same to a file
#include<fstream.h>
#include<conio.h>
void main()
{
ofstream fout;
char line[80];
fout.open("fname");
clrscr();
cout<<"\n enter line of text";
cin.getline(line,80);
fout<<line;
fout.close();
char ch;
cout<<"\n data entered in the file is\n";
ifstream fin;
fin.open("fname");
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
}
PUT()
- FUNCTION PUT() WRITES A CHARACTER TO A STREAM.
- THE FUNCTION TAKES A SINGLE CHARACTER TO THE STREAM.
EXAMPLE.
Ofstream fout.put(‘*’);
Will put * in the file to which stream fout is linked.

#include<fstream.h>
#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
ofstream fout("chars");
clrscr();
for(ch='A';ch<='Z';ch++)
{
cout.put(ch);
fout<<ch;
}
fout.close();
ifstream fin("chars");
cout<<"\n characters in file are";
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
}
WRITE()
- OVERLOADED STREAM INSERTION FUNCTION AND FUNCTIONS LIKE
PUT() WRITE DATA TO THE TEXT FILES IN WHICH NUMERIC DATA
LIKE INTEGER AND REAL NUMBERS ARE FIRST TRANSLATED INTO
CHARACTER STRINGS BEFORE THEY ARE WRITTEN TO FILES.
- IN BINARY FILES THE NUMBERS ARE WRITTEN AS THEY ARE
STORED IN THE RAM.
- WRITE() FUNCTION WRITES DATA TO THE BINARY FILE.
- FUNCTION WRITE() ALSO ALLOWS TO WRITE THE ENTIRE
STRUCTURE OR OBJECT OF THE CLASS IN THE FILE.
SYNTAX:
streamobject.write((char *)&objectname,sizeof(object));
-Here sizeof(object) finds out the total no. of bytes to be written
&objectname returns the reference of object name starting from where the specified
no. of bytes are to be written.
(char *)&objectname casts the reference of objectname to char type pointer before it’s
written on to the file.
fout.write((char *)&stud, sizeof(stud));

READ()
- FUNCTION read() CAN READ DATA FROM A BINARY FILE.
- IT CAN ALSO READ BLOCK OF DATA. A SINGLE READ STATEMENT
CAN READ ALL THE DATA MEMBERS OF A STRUCTURE VARIABLE
OR AN OBJECT.
SYNTAX
streamname.read((char *)&objectname,sizeof(object));
Here sizeof(object) finds out the total no. of bytes to be read.
&objectname returns the reference of object name starting from where the specified
no. of bytes are to be read.
(char *)&objectname casts the reference of objectname to char type pointer before it’s
read from the file.
fout.read((char *)&stud, sizeof(stud));
Program

#include<fstream.h>
#include<conio.h>
#include<iomanip.h>
class item
{
public:
int no;
char name[10];
int rate, qty;
void getdata();
void putdata();
int cal();
};
void item::getdata()
{
cout<<"\n enter item code";
cin>>no;
cout<<"\n enter item name";
cin>>name;
cout<<"\n enter rate";
cin>>rate;
cout<<"\n enter quantity";
cin>>qty;
}
void item::putdata()
{
int amount;
cout<<setw(5)<<"\n item code";
cout<<setw(10)<<"item name";
cout<<setw(10)<<"rate";
cout<<setw(10)<<"quantity";
cout<<setw(10)<<"amount";
cout<<endl;
cout<<setw(10)<<no;
cout<<setw(10)<<name;
cout<<setw(10)<<rate;
cout<<setw(10)<<qty;

amount =cal();
cout<<setw(10)<<amount;

int item::cal()
{
int t=rate * qty;
return t;
}
void main()
{
item it;
fstream fout;
clrscr();
fout.open("item.dat",ios::binary|ios::out);
char ans='y';
while(ans=='y')
{
it.getdata();
fout.write((char *)&it,sizeof(it));
cout<<"\n wish to enter more data";
cin>>ans;
}
fout.close();
fout.open("item.dat",ios::binary|ios::in);
int count=0;

while(!fout.eof())
{
fout.read((char *)&it,sizeof(it));
count++;
}
fout.close();
fout.open("item.dat",ios::binary|ios::in);
cout<<"no. of records"<<count-1;

for(int i=0;i<count-1;i++)
{
fout.read((char *)&it,sizeof(it));
it.putdata();
}

fout.close();
}

RANDOM ACCESS FILES


- USING RANDOM ACCESS DATA CAN BE DIRECTLY OR RANDOMLY BE
WRITTEN ON TO THE FILE OR CAN ALSO BE READ RANDOMLY.
FEW C++ FUNCTIONS ARE AVAILABLE TO MAKE THE RANDOM
OPERATIONS POSSIBLE.
SEEKG()
- SEEKG () FUNCTION ALLOWS TO MOVE THE FILE POINTER TO THE
SPECIFIED BYTE IN THE FILE.
SYNTAX:
seekg(offset);
seekg(offset,flag);
- IN THE FIRST FORM THE FILE IS POSITIONED SKIPPING OFFSET
NUMBER OF BYTES FROM THE BEGINNING OF THE FILE.
- THE SECOND FORM OF THE FUNCTION ALONG WITH THE OFFSET
REQUIRES A SECOND ARGUMENT WHICH DETERMINES THE ORIGIN
FROM WHICH THE OFFSET WILL BE MEASURED.
- FLAG MAY BE ASSIGNED THE VALUE 0,1 OR 2 IF OFFSET IS REQUIRED
TO BE MEASURED FROM THE BEGINNING , CURREN FILE POSITION AND
THE END OF THE FILE.
seekg(0);
seekg(k,ios::cur);
- If FOR EXAMPLE IF ONE WANTS TO REACH 10th RECORD DIRECTLY THE
VALID COMMAND IS:
seekg(9*sizeof(r));
Will position the file pointer to the beginning of the 10th record.
PROGRAM

FUNCTION seep()
FUNCTION seekg() POSITIONS THE FILE FOR READING DATA FROM IT,
FUNCTION seetp() POSITIONS FILE FOR WRITING TO IT.

ERROR HANDLING
- SOMETIMES DURING FILE OPERATIONS, ERRORS MAY APPEAR.
- TO CHECK FOR ERRORS AND TO ENSURE SMOOTH PROCESSING, C++
FILE STREAMS INHERIT “STREAM STATE” MEMBERS FROM THE ios
CLASS THAT STORE THE INFORMATION ON THE STATUS OF A FILE
THAT IS BEING CURRENTLY USED.
TABLE OF FUNTIONS WITH THEIR MEANINGS
FUNCTION MEANING
Int bad() Returns non-zero value if an invalid operation is attempted or any
unrecoverable error has occurred. Otherwise returns zero value and
it is possible to recover from any other error reported and continue
operation.
int eof() returns non-zero if end of file is encountered while reading
otherwise returns zero.
int fail() returns nonzero when an input or ouput operation has failed.
int good() retruns non-zero if no error has occurred. this means all the above
functions are false. when it returns zero no further operations can
be carried on.
clear() resets the error state so that further operations can be attempted.
Few examples of using above mentioned functions:

ifstream fin;
fin.open(“master”);
while(!fin.fail())
{
cout<<”it’s okey”;
}
if(fin.eof())
{
exit(1);
}
else if(fin.bad())
{
cout<<”fatal error”;
else
fin.clear();

You might also like