How do I copy files in Visual C ++?

I am using Visual C ++. How can I copy the contents of this file to another file?

UINT32 writeToLog(wstring log)
 {
    wfstream file1 (LOG_FILE_NAME, ios_base::out);  
    file1 << log;       
    file1.close();

     // want to copy file1 to file2

     return 0;
 }

      

+2


a source to share


3 answers


What exactly do you want to do? If you need a copy of the data, you can read it and write it again. If you really want a copy of the file, you must use special OS calls.

In many cases, reading data in files and then reusing them in another file is a fairly close approximation of a copy - for example:

ifstream file1(...);
ofstream file2(...);
std::copy(istream_iterator<char>(file1),istream_iterator<char>(),ostream_iterator<char>(file2));

      



However, it really isn't a copy - it creates a new file with the same content. It will not handle hard links or symbolic links correctly, it will not handle metadata correctly, and it will "copy" the file by default .

If you need a copy of a file on Windows, you should call one of CopyFile , CopyFileEx, or CopyFileTransacted depending on your exact requirements.

+11


a source


The C ++ standard has no facility for copying files other than reading the file into memory and writing it to another file. When using Windows, you can use the CopyFile function - other OSs have similar OS-specific functionality.



+3


a source


The above code from Joe Gauterin didn't work for me. I was trying to copy the .tga image file, so maybe something about istream_iterator<char>

screwed it up. I used instead:

ifstream file1(...);
ofstream file2(...);
char ch;
while(file1 && file1.get(ch))
{
  file2.put(ch);
}

      

0


a source







All Articles