How to "save as" an existing text file

Can someone please help me on this?

I need to make a copy of an existing .txt file and save it under a different name. The original file needs to be preserved so a simple "rename" can't do the trick. I've been searching on the web and the only way I found was to read the existing file into some sort of a data structure, e.g. vector<string>, then dump the whole thing into a new .txt file.

I'm a bit concerned that the files are pretty big so is there a better way of doing this, please? Many thanks.
See CopyFile (http://msdn.microsoft.com/en-us/library/aa363851(VS.85).aspx ) if you're on windows...
Last edited on
The STL copy() algorithm works for just this kind of thing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <algorithm>
#include <fstream>
#include <iterator>
#include <string>

bool copy_file( const std::string& source, const std::string& destination )
  {
  std::ifstream inf( source.c_str(), std::ios::binary );
  std::ofstream outf( destination.c_str(), std::ios::binary );

  if (!inf || !outf) return false;

  std::copy(
    std::istream_iterator <unsigned char> ( inf ),
    std::istream_iterator <unsigned char> (),
    std::ostream_iterator <unsigned char> ( outf )
    );

  return inf.eof() && outf.good();
  }

Hope this helps.
It's very helpful! Thank you both.
Topic archived. No new replies allowed.