Copying a file
Have a look at the code
#include "iostream.h"
#include "conio.h"
#include "fstream.h"
void main()
{
clrscr();
int cnt=0;
ifstream in("file1.txt"); // source file (must be existing)
ofstream out("file2.txt"); // target file (will be automatically created)
char ch;
in.get(ch); // reading from the source file
while(in)
{
out.put(ch); // writing in the target file
in.get(ch); // reading the next char from the source file
cnt++;
}
cout<<"\nCopied "<<cnt "<<"" characters="" characters?;="" copied.
in.close();
out.close();
}
Output : (Assuming that the source file has 30 characters)
Copied 30 characters
To copy the contents of a file to another, we will use both get() and put() in the same code. To make this program, we will open two files at the same time , the source file(the one that we want to copy) and the target file(the file that will contain the copied data). The source file will be opened in the read mode(using ifstream) whereas the target file will be accessed in the write mode(using ofstream).
Have a look at the code
#include "iostream.h"
#include "conio.h"
#include "fstream.h"
void main()
{
clrscr();
int cnt=0;
ifstream in("file1.txt"); // source file (must be existing)
ofstream out("file2.txt"); // target file (will be automatically created)
char ch;
in.get(ch); // reading from the source file
while(in)
{
out.put(ch); // writing in the target file
in.get(ch); // reading the next char from the source file
cnt++;
}
cout<<"\nCopied "<<cnt "<<"" characters="" characters?;="" copied.
in.close();
out.close();
}
Output : (Assuming that the source file has 30 characters)
Copied 30 characters
The above code will open two files - source(file1.txt) and target(file2.txt). The get() will read a character from the first file and store it in the variable "ch". The put() will copy the content of the variable "ch" into the target file. The process will continue till the first file gets completely read.Once the program completes its execution we can open the target file to see if the copy was correct or not.
I am a fresher and thanks a ton for the valuable education! Please keep updating!
ReplyDeletehp 1020 driver
Thanks for appreciating sarabose !!
ReplyDelete