I tried to write up a test program that uses std::copy and istream_iterator to copy one text file to another. But it doesn't work because the '\r' and '\n' in the file are lost. I've tried opening the input and output files in text mode and I've tried opening them in binary mode. The results are the same. Anyone know why this doesn't work correctly?

#include <Windows.h>
#include <iostream>
#include <fstream>
#include <iterator>
using namespace std;

bool ReadFile(const char* filename)
    ifstream in(filename, ios::binary);
    if( !in.is_open() )
        return false;
    istream_iterator<char> begin(in);
    istream_iterator<char> end;

    ofstream out("out.txt", ios::binary);
    if( !out.is_open() )
        return false;
    ostream_iterator<char> begin2(out);
    copy(begin, end, begin2);
    return true;

int main()


Here is what the output file looks like


5 Years
Discussion Span
Last Post by vijayan121
Featured Replies
  • 1

    >> why this doesn't work correctly? The input stream has the [ICODE]skipws[/ICODE] format flag set, use [URL="http://www.cplusplus.com/reference/iostream/manipulators/noskipws/"]noskipws[/URL] to clear the flag. Read More


If the intent was to use std::copy and stream iterators, I have nothing to add.

If the intent was to write a function to copy a file, this would be easier and also more efficient.

bool copy_file( const char* input_file, const char* output_file )
{ return std::ofstream( output_file ) <<  std::ifstream(input_file).rdbuf() ; }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.