Sie sind auf Seite 1von 6

File Handling

A file is a bunch of bytes stored on a storage device like a tape or a magnetic disk. In C++ file
input / output facilities are implemented through a component header file of C++ standard library
called fstream.h. A file at its lowest level is interpreted as a sequence of bytes.

The fstream.h header file has 3 classes that help to perform file input and output.
Ifstream class for input (to read a file) Ifstream (the input stream ) reads the data from the file
and supplies it to the program.
Ofstream class for output ( to write on a file) Ofstream receives data from the program and
writes the received data to the file.
Fstream for both input and output (to both read and write on to a file)

C++ contains a set of classes that define the file handling functions. These classes are declared
within fstream.h. So we have to include this header file when working with files. Fstream is
derived from iostream the header file which manages console I/O operations.

Fstream.h header file contains the classes ifstream, fstream.,ofstream which are derived from
fstreambase class and provides operations common to both input and output. It also contains
open( ) and close( ) functions.

Ifstream inherits get(), getline( ), read( ) , seekg( ) and tellg( ) , close(), open( )
Ofstream inherits put( ), write( ), seekp( ), tellp( ), open( ), close( )
Fstream inherits all the functions.

Data files
A text file stores information in ACII characters. In text files each line of text is terminated with
a special character known as EOL. In text files some internal translations take place when this
EOL character is read or written.

A binary file is file which stores information in the same format as it is stored in the memory.
There is no delimiter. Also no translations take place. Binary files are faster and easier to read.

Opening and closing files

Opening of files can be achieved in two ways
Using constructor function of the stream class ifstream f1(“File.txt”);
Using open() ifstream f1;“file.txt”);

Filemode describes how a file is to used.

1) ios::in file is opened for writing
1) ios::out file is opened for writing. If the file does not exist, it is created.
2) ios::ate opens the file at end. Can write anywhere in the file.
3) ios::app causes the output to be appended to the end of the file.
4) ios::trunc causes the contents of the file to be destroyed and truncates the file to zero
length. If the file
does exist it gives an error.
5) ios::nocreate File should exist from before for open( ) to work, otherwise it will give an
error message.
6) ios::noreplace File should not exist from before for open( ) to work., otherwise open( ) fails.
Used when you want to create new file
7) ios::binary Causes file to be opened in binary mode.

To close a file f1.close( )

Get( ) is used to read single characters from the user while getline( ) is used to read strings.
Put( ) is used to write one character onto the file. Get() and put( ) are byte oriented.

Getline(varname, size, delimiter).

e.g. char line[20]; getline (line, 20, ‘;’);
By default the delimiter is “\n”. The getline function reads characters form input stream and puts
them into the buffer until either size number of characters have been read or the delimiter is

1)Create 2 text files

#include<fstream.h> #include<conio.h>
void main( )
{ clrscr( ); char ch; fstream f1, f2;“First .txt”,ios::out);
f1<<”My school is Carmel Convent\n”;
f1<<”It is in Delhi”; f1.close();“First.txt”,ios::in);“Second.txt”,ios::out);
{ cout<<ch; f2.put(ch) ;}

To get rollno, marks of student from user and store it into a file called myfile.dat.
#include <fstream.h> #include<conio.h>
ofstream fout;“Marks.dat”);
char ans = ‘Y’; int rollno; float marks;
while( ans==’y’ || ans= = ‘Y’)
{ cout<<”Enter roll :” ; cin>>rollno; cout<<”Enter name”; gets(name); cout<<”Marks”;
cout<<’Wish to enter more”; cin>>ans;
} fout.close( ); }

To read the contents of file STORY.TXT and display the no of alphabets , vowels, no of
words and no of empty spaces

#include<fstream.h> #include<conio.h> #include <ctype.h>

Ifstream f1;“Story.txt”, ios::noreplace); char ch; int calpha= cvow= cspace=0;
If(!fin) { cout<< “File does not exist” return; }
While (fin.get(ch)
{ ch = toupper(ch)
if (isalpha)
{ calpha++;
if ( ch == ‘A’ || ch==”E’ || ch == ‘I’ || ch ==’O’ || ch ==’U’)
if (ch == ‘ ‘) cspace ++;
cout<<”No of alpabets” <<calpha<<endl;
cout<<”No of vowels”<<cvow<<endl;
cout<<”No of spaces”<<cspaces;
cout<<”No of words”<<++cspaces;
fin.close ( );

To create and display test file line by line and count no of words beginning with B.
#include < fstream.h>
void main( )
ofstream fn;“Story.txt”,ios::out); fn << “Hello little boy \n”; fn<<”These are your
books”; fn.close ( );
ifstream fillin;
int countb = 0;“Story.txt); char line[80];
if(!fin) { cout<< “Error in opening file”; return -1; }
while(fillin.getline(line,80, ‘\n’) cout<< line<<’\n’;
while(fillin.getline(line, 80,’ ‘)
if (line[0]== ‘B’) countb++; cout<<”no of words beginning with b are”<<countb;

TO convert from uppercase to lower and vice vesa

#include<fstream.h> #include<conio.h> #include<ctype.h>

void main()
{ clrscr();
fstream f1;"olddata.txt",ios::in|ios::out);
fstream nf;"newdata.txt",ios::out);
char ch;
f1<<"INteRneT RETRETE";
cout<<endl<<"the 'oldData.txt file contains"<<endl;
{f1.get(ch); cout<<ch;
if(ch>64 && ch<91) ch=tolower(ch);
if(ch>96&&ch<123) ch=toupper(ch);
nf.put(ch); }
cout<<endl<<"the 'newData.txt'file contents are"<<endl;
nf.seekg(0); while(nf)
{ nf.get(ch); cout<<ch; } getch(); }

Read ( ) and write ( ) functions are used to read and write blocks of binary data. Used when
classes/ structures are used in binary files. *)&obj, sizeof(student);

Fout .write(char *) &obj, sizeof (student);

Use of read( ) and write( )

#include<fstream.h> #include<conio.h> #include<ctype.h> #include<string.h> #include<stdio.h>

class emp
{ int eno; char name[15]; float sal;
void getdata(); void display(); void search(int); }e1;

void emp::getdata()
{ ofstream f;"empf.dat",ios::app||ios::binary);
cout<<"Enter the eno"; cin>>eno;
cout<<"enter the name"; gets(name);
cout<<"Enter the salary"; cin>>sal;
f.write((char*)this,sizeof(emp)); f.close();

void emp::display()
{ fstream fin;"empf.dat",ios::in||ios::binary); fin.seekg(0);
cout<<"\nEno"<<'\t'<<eno; cout<<"\nEmployee name"; puts(name);
cout<<"\nEmployee sal"<<sal;
void emp::search(int rno)
{ fstream fin;
int loc;"empf.dat",ios::in||ios::binary);
cout<<"\nENO "<<eno;
cout<<"\nEmployee name :"<<name;
cout<<"\nEmployee salary :"<<sal;
void main()
int c,rno;

cout<<"\n\n1. Enter the data"
<<"\n\n2. Display data"
<<"\n\n3. Search"
<<"\n\n4 Exit"
<<"\n\n Enter your choice";
cin>> c;
{ case 1 : e1.getdata();
case 2 : fstream fin;
case 3 : cout<<"Enter the record no to be searched ";
case 4 : cout<<"Bye! See you";

default : cout<<"Enter the corrct choice";

} while(c!=4);

File Pointers and Random Access

Every file has 2 pointers 1) get( ) and 2) Put( ) which tell the current position in the file where
writing or reading will take place. These pointers help in random access in files.

Seekg( ) and tellg( ) functions allow you to examine the get( ) pointer. (fstream)
Seekp( ) and tellp( ) perform these operations on the put pointer. (ofstream)

Fin.seekg( 0 ) beginning of the file

Fin.seekg( 30, ios:: beg) – byte no 30 from beginning of the file.
Fin.seekg(20, ios:: end)
Fin.seekg( 2, ios:: curr)

Tellg( ) and tellp( ) return the position of the put and get pointer.
Read a text file and display the no of bytes in it.
Fstream fi;
F1.seekg(0, ios::end) ;
Int no_of_bytes = fin.tellp(); cout<<no_of_bytes;

Q1. void main ()

{ char ch = ‘A’;
fstream fileout(“data.dat”, ios::out); fileout<<ch;
int p = fileout.tellg( ); cout<<p;}

what is the output if the file contains “ABCD” before the execution of the program

Function for modification

Void modify ( )
{ fstream fil;
item obj;“Item.dat”,ios::binary|ios::in|ios::out|ios::ate);
int lino,rec=0, flag =0;
cout<<”Enter the item no to modify”; cin>>lino;
while ( *) &obj, sizeof(item)))
{ rec++;
if(ino == lino) cout<< “Enter new details”;
{ obj.getdata( );
file.seekp((rec-1) * sizeof(student), ios::beg)
file.write(char*) &obj; sizeof (item));
flag = -1;
if(flag == 0) cout<<”Record does not exist” else cout<<”\n Modified”;
fil.close( );

Q Following is a structure of each record in a data file named “Colony.dat”

Struct Colony
{ char colony_code [10]; char colony_name[10]; int no_of_people; };

Write a function in C++ to update the file with a new value of no_of people. The value of
colony_code and No_of_people are read during the execution of the program.