Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I have a problem in my program of copying contains of one file into another file. It runs quit good but the problem is it can't show a proper output. When the contains of file "Name.txt" has coppied to another file then it doesn't shown the copied contains. Please tell me what I am missing.
The Program is follows:

/* WAP to copy containt of one file into another file */

C++
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
ifstream infile;
ofstream outfile;
clrscr();
char infileName[10];
char outfileName[10];
char in_char;

outfile.open("Name.txt",ios::out);
outfile<<"Good\n";
outfile<<"To\n";
outfile<<"See\n";
outfile<<"You\n";
outfile.close();

cout<<"\nEnter file name to copy : ";
cin>>infileName;
infile.open(infileName,ios::in);
if(!infile)
{
cout<<"\nFile "<<infileName <<" not found ";
getch();
exit(0);
}
while(infile.get(in_char))
   cout<<in_char;
   infile.close();
cout<<"\nEnter name of new file in which you want to copy "<<infileName<< " : ";
cin>>outfileName;
outfile.open(outfileName,ios :: out);
if(!outfile)
{
cout<<"\n\aError in opening of "<<outfileName;
getch();
exit(0);
}
cout<<"\n\a\nFile Copy is in progress ......... ";
while(infile.get(in_char))
cout<<"\n\a\nFile Copy Sucessfull ...... ";
cout<<"\n\nNew File is : "<<outfileName;
cout<<in_char;
infile.close();
outfile.close();
getch();
}

Output:
Enter file name to copy : Name.txt
Good
To
See
You

Enter name of new file in which you want to copy Name.txt : Read.txt

File Copy is in progress.......

File Copy Sucessfull.....

New File is : Read.txt


Now, here it should prints the contains of Read.txt but it can't prints them. I tried but didn't get anything, So please give me some hint.
Thanks...

[EDIT: Added code block formatting]
Posted
Updated 9-Nov-14 0:43am
v3

1 solution

When trying to perform the copy operation, your infile has already been closed. You must re-open the input file before copying or don't close it (rewind the stream in this case).

You are also not performing any write operation to the output file. It seems that this operation is missing after the second read line
while(infile.get(in_char))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900