Copying contents of one file to another.
Mar 25, 2009 at 4:29pm UTC
Hi guys.
Just wondering if anyone could help me with a problem I am having with some code. I am trying to get the contents of one file to be copied to another ( both files are specified by the user) All is well and good except, when the contents of the first file is attempted to be copied to the second file, it is only copying the first line. Could someone help me. Here is my code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string filename1,filename2;
ifstream ipf;
char c;
char Buffer[512];
for ( int i = 0; i < 512; i++ )
{
Buffer[i] = ' ' ;
}
cout << "Please enter the filename of the first file" << endl;
cin >> filename1;
ipf.open(filename1.c_str());
if (!ipf.is_open())
{
cout << " Oops! couldn't open file :" << filename1;
}
else
{
cout << " Please enter the filename of the second file which you wish contents to be copied to" << endl;
cin >> filename2;
}
ipf.getline( Buffer, 512 );
ipf.close();
ofstream opf;
opf.open(filename2.c_str());
if (!opf.is_open())
{
}
opf.write( Buffer, 512 );
opf.close();
system("pause" );
return 0;
}
Thanks :)
Mar 25, 2009 at 5:01pm UTC
1 2 3 4
ipf.open(filename1.c_str());
// ...
ipf.getline( Buffer, 512 );
ipf.close();
This code reads a line of upto 512 bytes in length an then closes the file.
You need to repeatedly read from the input file until you've reached the end and write those to the output file.
Additionally, if you're using a Microsoft platform, you need to open the file in binary mode or because of end of line encoding differences:
ipf.open(filename1.c_str(), std::ios_base::binary);
Mar 25, 2009 at 7:21pm UTC
Got it working , Thanks alot :) .
Topic archived. No new replies allowed.