General File Handling Programs
Question:25
Write a C++ program to copy the contents of one file onto another file.
Sol:
/*
copy contents into another file
*/
#include<iostream>
#include<fstream>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
void transfer(char *sfile,char *tfile)
{
char ch;
ifstream abc;
ofstream out1;
abc.open(sfile);
if(abc.fail())
{
cout<<"Unable to open the source file"<<endl;
exit(1);
}
out1.open(tfile);
if(out1.fail())
{
cout<<"Unable to open the target file"<<endl;
exit(1);
}
//to copy the contents
while(!abc.eof())
{
abc.get(ch);
out1.put(ch);
}
abc.close();
out1.close();
}
void display(char *file)
{
ifstream pqr;
char ch;
cout<<"The contents of the file "<<file<<" are "<<endl;
pqr.open(file);
if(pqr.fail())
{
cout<<"Unable to open the file "<<file<<endl;
exit(1);//return;
}
while(!pqr.eof())
{
pqr.get(ch);
//cout<<ch;
cout.put(ch);
}
pqr.close();
}
int main()
{
char sfile[10],tfile[10];
cout<<"Enter source file name ";
cin>>sfile;
cout<<"Enter target file name ";
cin>>tfile;
transfer(sfile,tfile);
display(sfile);
display(tfile);
getch();
return(0);
}
Question:26
Write a C++ program to read the contents of a file and perform the following:
1. copy all alphabets to a file named “alpha”
2. copy all lower case alphabets to a file named “lower”
3. copy all upper case alphabets to a file named “upper”
4. copy all digits to a file named “digits”
Further display contents of all the file.
Sol:
/*
Main File "data"
lower
upper
digit
alpha
*/
#include<iostream>
#include<fstream>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
void transfer()
{
char ch;
ifstream abc;
ofstream out1,out2,out3,out4;
abc.open("data.txt");
if(abc.fail())
{
cout<<"Unable to open the Source file"<<endl;
exit(1);
}
out1.open("alpha");
if(out1.fail())
{
cout<<"Unable to open the alpha file"<<endl;
exit(1);
}
out2.open("lower");
if(out2.fail())
{
cout<<"Unable to open the lower file"<<endl;
exit(1);
}
out3.open("upper");
if(out3.fail())
{
cout<<"Unable to open the upper file"<<endl;
exit(1);
}
out4.open("digit");
if(out4.fail())
{
cout<<"Unable to open the digit file"<<endl;
exit(1);
}
while(!abc.eof())
{
abc.get(ch);
if(isalpha(ch)) //if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
out1.put(ch);
if(islower(ch))
out2.put(ch);
if(isupper(ch))
out3.put(ch);
if(isdigit(ch))
out4.put(ch);
}
abc.close();
out1.close();
out2.close();
out3.close();
out4.close();
}
void display(char *file)
{
ifstream pqr;
char ch;
cout<<"The contents of the file "<<file<<" are "<<endl;
pqr.open(file);
if(pqr.fail())
{
cout<<"Unable to open the file "<<file<<endl;
exit(1);//return;
}
while(!pqr.eof())
{
pqr.get(ch);
//cout<<ch;
cout.put(ch);
}
pqr.close();
cout<<endl;
}
int main()
{
transfer();
cout<<"Data Transfered"<<endl;
display("data.txt");
display("alpha");
display("lower");
display("upper");
display("digit");
getch();
return(0);
}




