The Database Managers, Inc.

Contact The Database Managers, Inc.


Use an RSS enabled news reader to read these articles.Use an RSS enabled news reader to read these articles.

How can I append a file to another file using STL algorithms and iterators?

A:  Try this:


#include <algorithm>
#include <fstream>

int main()
{
  std::ifstream in("fileforread.tmp");
  std::ofstream out("fileforappend.tmp",std::ios_base::app);

  std::istreambuf_iterator<char> src(in.rdbuf());
  std::istreambuf_iterator<char> end;
  std::ostream_iterator<char> dest(out);

  std::copy(src,end,dest);
}

Listing 1: Append a file to another using STL algorithms and iterators

The code in Listing 1 reads the contents of fileforread.tmp and appends it to fileforappend.tmp.

The src, end and dest objects were instantiated to make the std::copy() function easier to read and understand.

Part of the magic of this solution is the std::ios_base::app parameter on the instantiation of the out variable. It configures the out variable to append to the destination file.

The next part of the magic is in the std::copy() function. When std::copy() is passed three iterators, it copies everything in the range of the first iterator to the second iterator into the destination iterator.

In this example, it copies everying in the range of the src and end iterators into the dest iterator.

Notice some interesting points about this solution:

  1. The length of the file being read is not known. The instantiation of the end variable is only to create an iterator that can be passed to the std::copy() function.
  2. The length of the fileforappend.tmp file is also not known. The std::ios_base::app parameter provided all of the instructions the program needed to place the file's insertion pointer at the end of the fileforappend.tmp file.


Popular C++ topics at The Database Managers:

C++ FAQ Services | Programming | Contact Us | Recent Updates
Send feedback to: