3

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?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • 2
    you have to read from the input file, then write into the output file – taocp Oct 10 '14 at 15:31
  • `<< infile` will just be writing out the internal file handle identifier. e.g. at the time you ran your code, the `input.txt` handle had id 0x28fe78 – Marc B Oct 10 '14 at 15:32
  • 2
    Try `outfile << infile.rdbuf();` instead. – Jerry Coffin Oct 10 '14 at 15:35
  • Can you use an OS function to do this, like the Linux `cat` command? – Thomas Matthews Oct 10 '14 at 16:32
  • This is a subset of another question: http://stackoverflow.com/questions/10195343/copy-a-file-in-an-sane-safe-and-efficient-way – Thomas Matthews Oct 10 '14 at 16:35
  • That line is actually invoking the implicit conversion to `void*`. Before it was replaced with `basic_ios::operator bool()`in C++11, it returned `0` if `fail()` and otherwise some non-null pointer. So really it is implementation-defined what pointer is printed out. For example, in libstdc++ it returned `const_cast(this)` if `!fail()`. – David G Oct 10 '14 at 16:54

1 Answers1

7

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;
}
Kite
  • 651
  • 6
  • 16