• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 188
  • Last Modified:

combine two text files.

hi
i want to insert text from one file to another existing text file(to the end of the second file),could someone help me? example is perfect!
thanks.

0
shean85
Asked:
shean85
2 Solutions
 
jkrCommented:
You'd use

ifstream is;
ofstream os;

is.open ( "infile.txt");
os.open ( "appendfile.txt", ios_base::ous | ios_base::app); // open as "append"

while (!is.eof ()) { // read from input file

    string s;
    getline ( is, s);
    os << s.c_str (); // append to output file
}

os.close ();
is.close ();
0
 
itsmeandnobodyelseCommented:
Some minor supplements to the sample of jkr:

1. Use  

#include <fstream>
using namespace std;

2. Change ios_base::ous --> ios_base::out  

3.    os << s.c_str () << endl; // append to output file and add a linefeed character

Regards, Alex

0
 
mnashadkaCommented:
For a more C++ version, you can use iterator's and the copy algorithm:
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

void main(void)
{
  ifstream in("success.log"); // Open the input file
  in.unsetf(ios_base::skipws); // We want whitespace
  ofstream out("out.txt", ios_base::app | ios_base::out); // Open the output file
  copy(istream_iterator<char>(in), istream_iterator<char>(), ostream_iterator<char>(out)); // Copy the data from the ifstream to the ofstream
}
0
 
DanRollinsCommented:
Do you want to append the contents of second file to the end of the first file?
Or do you want to insert the contents of the second file at some other location in the first file?

-- Dan
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now