'How can I copy a text file into another? [duplicate]
How can I copy a text file into another? I tried this:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile("input.txt");
ofstream outfile("output.txt");
outfile << infile;
return 0;
}
This just ends up leaving the following value in output.txt
: 0x28fe78
.
What am I doing wrong?
Solution 1:[1]
You can save the content of the input file in a string and print the string into the output file. Try this:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main ()
{
ifstream infile("input.txt");
ofstream outfile("output.txt");
string content = "";
int i;
for(i=0; !infile.eof(); i++) // get content of infile
content += infile.get();
infile.close();
content.erase(content.end()-1); // last read character is invalid, erase it
i--;
cout << i << " characters read...\n";
outfile << content; // output
outfile.close();
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |