Copying a file to another file | File Handling C++

File Handling in C++

What are files and streams

Files are used to store data permanently whereas a stream is an abstraction that represents a device on which input and output operations are performed. A stream can basically be represented as a source or destination of characters of indefinite length.

copying a file
Basic Structure of File Handling

ofstream: This data type represents the output file stream an is used to create files and to write information to files

ifstream: This data type represents the input file stream and is used to read information from files.

fstream: This data type represents the file stream, and has the capabilities of both ofstream and ifstream which means it can create files, write data to files and read data from files.

To copy the substance of one file to the next file in C++ programming, you need to initially ask to the user to enter the source file to open the source file and after that request to enter the objective file to open the objective file and begin perusing the source file's substance character by character and put or compose the substance of the source file to the objective file character by character at the season of perusing.


C++ Program To Implement Copying Of Files

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
fstream f1;
string s;
char c;
f1.open("source.txt",ios::out);
cout<<"Enter the Contents of Source File : "<<endl;
getline(cin,s,'\n');
f1<<s;
f1.close();
fstream f2("dest.txt",ios::out);
f1.open("source.txt",ios::in);
while(f1.get(c))
f2<<c;
f2.close();
cout<<"Contents of Destination File : "<<endl;
f2.open("dest.txt", ios::in);
while(f2.get(c))
{
cout<<c;
}
f1.close();
f2.close();
return 0;
}
OUTPUT:
Enter the Contents of Source File :
Hey There. How are you?
Contents of Destination File :
Hey There. How are you?

tags :  copying a file, file handling C++, programs of c, programs of c++ ,

Post a Comment

Previous Post Next Post