You are on page 1of 2

To perform file processing in C+ + , header files <iostream> and <fstream> must

be included in your C++ source file.


Opening a File:
A file must be opened before you can read from it or write to it. Either the ofs
tream or fstream object may be used to open a file for writing and ifstream obje
ct is used to open a file for reading purpose only.
Closing a File
When a C++ program terminates it automatically closes flushes all the streams, r
elease all the allocated memory and close all the opened files.

//File copy
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
char c;
void main()
{ ifstream fin("in.txt");
ofstream fout("out.txt");
while(1)
{ fin>>c;
if(fin.eof()) break;
fout<<c;
}
cout<<"File copied";
getch();
}
in.txt
Anand

out.txt
Anand
Note: We have to create only in.txt. After executing this program, out.txt will
be created.
//Vowel count
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
char c;
int ac,ec,ic,oc,uc;
void main()
{ clrscr();
ifstream fin("in.txt");
ofstream fout("out.txt");
while(1)
{ fin>>c;
if(fin.eof()) break;
if((c=='a')||(c=='A')) ac++;
else if((c=='e')||(c=='E')) ec++;
else if((c=='i')||(c=='I')) ic++;
else if((c=='o')||(c=='O')) oc++;
else if((c=='u')||(c=='U')) uc++;
}
fout<<"Number of a "<<ac<<endl;
fout<<"Number of e "<<ec<<endl;
fout<<"Number of i "<<ic<<endl;
fout<<"Number of o "<<oc<<endl;
fout<<"Number of u "<<uc<<endl;
cout<<"Done-open out.txt and check";
getch();
}

//Total
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
char c;
int id,m1,m2;
void main()
{ clrscr();
ifstream fin("in.txt");
ofstream fout("out.txt");
fout<<"ID M1 M2 Total"<<endl;
while(1)
{ fin>>id>>m1>>m2;
if(fin.eof()) break;
fout<<id<<" "<<m1<<" "<<m2<<" "<<m1+m2<<endl;
}
cout<<"Done - Open and see out.txt";
getch();
}

You might also like