file I/O
Oct 3, 2009 at 12:54pm UTC
Hey guys,
Having a problem with my code, my program is supposed to copy the contents of one file into another. The program is creating the file which is supposed to be a copy of the other, but it is blank , could someone take alook at my code, and tell me what's up. Thanks.
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
// program to coopy contents of one file to another
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
ifstream myfile("myfile.txt" );
if (myfile.is_open())
{
while (!myfile.eof())
{
getline(myfile,line);
}
}
ofstream outfile("copy.txt" );
if (outfile.is_open())
{
outfile << line ;
}
myfile.close();
outfile.close();
return 0;
}
Oct 3, 2009 at 12:59pm UTC
First you loop to get all the lines of the source file into
line (the last of which is the empty line).
Once done that, you write the last
line read from the source (which is empty) to the destination file.
See where the error is?
Also, don't loop on
ifstream ::
eof () -- it is dangerous.
1 2 3 4 5 6 7 8 9
ifstream srcfile( "myfile.txt" );
ofstream destfile( "copy.txt" );
string line;
while (getline( srcfile, line ))
{
destfile << line << endl;
}
destfile.close();
srcfile.close();
Keep in mind this only works for ASCII text files, and may not produce the same file as the original. For an exact copy, you need to use binary mode:
1 2 3 4 5 6 7 8 9
ifstream srcfile( "myfile.txt" , ios::binary );
ofstream destfile( "copy.txt" , ios::binary );
char c;
while (srcfile.get( c ))
{
destfile.put( c );
}
destfile.close();
srcfile.close();
Hope this helps.
Last edited on Oct 3, 2009 at 1:00pm UTC
Oct 3, 2009 at 1:16pm UTC
Thanks alot Duoas, one more question if I may. At the moment the program is only copying the one line even though i have "\n" at the end of the line, any ideas?
Oct 3, 2009 at 1:18pm UTC
Doesn't matter got it working :) I forgot to leave a space between the \n and the end of the line.
Thank you.
Last edited on Oct 3, 2009 at 1:18pm UTC
Topic archived. No new replies allowed.