merging contents of files

i need to write a c++ code which can merge contents of several .txt files into a single file. i used the following code , it works but after merging the result file contains the contents merged twice.I think it over writes the result.I want to do it without using command line.

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
std::ofstream("merge.txt");
system("type *.txt >> merge.txt");
system("pause");
return 0;
}

DO not ever use system()! Now I even cannot test my guess because I not on Windows right now. And there is several other problems which could arise using your code in not-english Windows versions.

What probably happens:
let's say we have three files "from1.txt", "from2.txt", "merge.txt"
When you call "type *.txt >> merge.txt" it will do:
1
2
3
type from1.txt >> merge.txt
type from2.txt >> merge.txt
type merge.txt >> merge.txt

It appends itself to itself: essentually doubles.
can you please provide me c++ code for ot
can you plz provide me c++ code for this problem
Assuming it is Windows, something like this:
1
2
3
4
5
6
7
8
9
10
11
12
#include <cstdlib>
#include <string>

int main()
{
    const std::string path = "C:\\some_dir\\another_dir\\" ;
    const std::string srce_pattern = "*.txt" ;
    const std::string dest_file_name = "merge.txt" ;

    std::system( ( "del " + path + dest_file_name ).c_str() ) ;
    std::system( ( "copy /a " + path + srce_pattern + " " + path + dest_file_name ).c_str() ) ;
}


Note: There is nothing wrong in using std::system() or in general one program invoking another program (fork/exec, CreateProcess etc.).

In security concious code, precautions have to be taken:
The environment (PATH etc) has to be sanitized before invoking external programs.
If the data to be passed to external programs (the command string in std::system()) come from unreliable sources, it has to be sanitized too.
And privileges have to be dropped to the minimum level required before invocation (do not run as root etc.)

Doing all this is somewhat difficult; so if an alternative is available (for example library calls) it is better to use that rather than invoking an external program to do the job.
Topic archived. No new replies allowed.