You are on page 1of 6

• A file is a collection of related data stored in a particular area on the disk

• A program typically involves the following kinds of data communication
– Data transfer between the console unit and the program
• Input stream – extracts data from the file

File handling

– Data transfer between the program and a disk file
• Output stream – inserts data to the file

Classes for file stream operations
– C++ contains a set of classes. These includes ifstream, ofstream and fstream. These classes are derived from fstreambase and from the iostream class
• Fstreambase – contains open(), close() functions • Ifstream – get(), read(), seekg(), tellg() • Ofstream – put(), seekp(), tellp() & write()

Opening and closing a file

• •

The class ofstream is used to create the output stream
– – Ofstream outfile(“results”) ifstream infile(“salary”)

The class ifstream is used to create the input stream Disconnect salary from infile
– Outfile.close();

Int main() { ofstream outf(“item”); char name[30]; cin>>name; outf<<name; float cost; cin>> cost; outf<<cost; //write cost to file item outf.close(); ifstream inf(“item”); inf>>name; //read name from the file cout<<name; inf.close(); return 0;

}

Opening files using open()
• To open multiple files that use the same stream object
– File-stream-class stream-object; stream-object.open(“file name”);

– Ofstream outfile; outfile.open(“DATA1”); //connect stream to DATA1

#include<iostream.h> #include<stdlib.h> int main() { const int size=80; char line[size]; ifstream fin1, fin2; fin1.open(“country”); fin2.open(“capital”);

for(int i=0; i<=10; i++) { if(fin1.eof() != 0) { cout<<“exit from country \n”; exit(1); } fin.getline(line, size); cout<<“capital of ”<<line; if(fin2.eof())!=0) { cout<<“Exit from capital”; } fin2.getline(line, size); cout<<line<<“\n”;

} return 0; } • •

Eof – end of file condition for preventing any further attempt to read data from the file it’s a member function of IOS class

• File mode

– Open function has two arguments – Stream-object.open(“file name”, mode);
– – – – Ios:: app Ios::ate Ios::in Ios::out append to end of file go to end of line on opening opening file for reading only opening file for writing only

– EX: fout.open(“data”, ios::app);

• FILE POINTERS
• Manipulation of file pointer
– – – – Seekg() Seekp() Tellg() Tellp() – Input pointer – Output pointer

• Sequential input & output operations
– Put() – writes a single character to the associated stream – Get() – reads a single character from the associated stream

• TEMPLATES
– A template can be consider as a kind of macro – Template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or function – Template <class T>