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() )
    {
        in.close();
        return false;
    }
    ostream_iterator<char> begin2(out);
 
    copy(begin, end, begin2);
    return true;
}

int main()
{

    ReadFile("test2.cpp");
}

Here is what the output file looks like

//test2.cpp:Definestheentrypointfortheconsoleapplication.//#include"stdafx.h"#include<Windows.h>#include<iostream>#include<fstream>#include<iterator>usingnamespacestd;//typedefvoid(WINAPI*PGNSI)(constchar*);boolReadFile(constchar*filename){ifstreamin(filename,ios::binary);if(!in.is_open()){returnfalse;}istream_iterator<char>begin(in);istream_iterator<char>end;ofstreamout("out.txt",ios::binary);if(!out.is_open()){in.close();returnfalse;}ostream_iterator<char>begin2(out);copy(begin,end,begin2);returntrue;}intmain(){ReadFile("test2.cpp");}#if0intmain(){charbuf[255]={0};DWORDdwError=0;HMODULEh=LoadLibrary("C:\\dvlp\\testdll\\Debug\\testdll.dll");if(h==NULL){dwError=GetLastError();FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,0,dwError,0,buf,sizeof(buf),0);cout<<"LoadLibrary()failed\n";cout<<buf<<'\n';return1;}PGNSIpGNSI=(PGNSI)GetProcAddress(h,"?ReadFile@@YG_NPBD@Z");if(pGNSI!=NULL){pGNSI("test2.cpp");}else{dwError=GetLastError();FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,0,dwError,0,buf,sizeof(buf),0);cout<<"GetProcAccress()failed\n";cout<<buf<<'\n';}}#endif

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.