File Handling in C++
File Handling in C++
C++
Files (Streams)
Data
PROGRAM
Input
Output
Stream
Stream
>>
DEVICES OR <<
(Extraction
(Insertion
operator) FILES operator)
Data
istream class ostream class
The following classes in C++
have access to file input and
output functions:
ifstream
ofstream
fstream
The Stream Class Hierarchy
NOTE : UPWARD ARROWS INDICATE
THE BASE CLASS
ios
Ifstream Ofstream
fstream
Open() Open()
Tellg() Tellp()
Seekg() Seekp()
DIFFERENT FILE OPERATIONS
OPENING A FILE
CLOSING A FILE
READING FROM A FILE
WRITING ON A FILE
CHECKING FOR END OF FILE
OPENING A FILE
(Associating a stream with a file)
The mode can combine two or more modes using bit wise
or ( | )
Checking For Successful File Opening
ifstream transaction(“sales.dly”);
if (transcation == NULL)
{
cout<<“unable to open sales.dly”;
cin.get(); // waits for the operator to press any key
exit(1);
}
Closing of File
Stream_name.close();
e.g., transaction.close();
Types of Files
k bytes ^
File pointer
Begin End
^
Offset from Begin
^
Offset from Begin
^
Offset from end
^
Offset from current
position
The seekg() function with two argument
//
//clrscr();
getch();
#include <fstream.h> cout <<"reading from created file \n";
#include <conio.h> infl.open("try.txt");
#include <stdio.h> out.open("cod.dat");
void main() //**********************************
{
c=infl.get();
//clrscr(); do
char c,d,ans; { d=c+1;
char str[80]; cout<<c<<d<<'\n';
ofstream outfl("try.txt"),out("cod.dat"); out.put(d);
c= infl.get();
ifstream infl;
}
do while (c!='\0');
{ cout<<"please give the string : "; out<<'\0';
gets(str); infl.close();
outfl<<str; outfl.close();
getch();
cout <<"do you want to write more...<y/n> : ";
//*********************************
ans=getch(); }
}
while(ans=='y');
outfl<<'\0';
outfl.close();