Oct 16, 2017 at 6:07pm UTC
I want to merge two files such that contents of second file are appended to contents of first.The code is behaving very weird.
My code logic:
create first file
create second file
create a file named "new" which has contents of first and then second in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#include<iostream>
#include<fstream>
using namespace std;
char filename[100];
void write()
{
char filename[100],line[80],ch;
cout<<"Enter name of file" ;cin.getline(filename,100);
cout<<endl;
ofstream w1;
w1.open(filename);
do
{
cout<<"Enter line" ;cin.getline(line,80);
w1<<line;
cout<<endl;
cout<<"Enter more line?(y/n)" ;cin>>ch;
cout<<endl;
}while (ch=='y' );
w1.close();
}
void read()
{
char s[80];
ifstream r1;
r1.open(filename);
while (r1>>s)
{
cout<<s<<endl;
}
r1.close();
}
void merger()
{
fstream s1("new" ,ios::out|ios::app);
char s[80],l[80];
ifstream q1;
ifstream w1;
q1.open(filename);
w1.open(filename);
while (q1>>s)
{
s1>>s;
}
while (w1>>l)
{
s1>>l;
}
w1.close();
s1.close();
q1.close();
remove(filename);
rename("new" ,filename);
}
int main()
{
cout<<"Enter first file" <<endl;
write();
cout<<"First file" <<endl;
read();
cout<<"Enter second file" <<endl;
write();
cout<<"Second file" <<endl;
read();
cout<<"Merged file" <<endl;
merger();
}
Last edited on Oct 16, 2017 at 6:30pm UTC
Oct 16, 2017 at 6:18pm UTC
Your code doesn't call your merging function.
Oct 16, 2017 at 6:31pm UTC
i edited it now.something happened while pasting
Oct 16, 2017 at 6:36pm UTC
Your merger function only opens one of the files. But it opens that file twice.
fstream s1("new" ,ios::out|ios::app);
What's this for? Looks like you create a new, empty file and then try to read from it. Should you be writing to it?
Last edited on Oct 16, 2017 at 6:36pm UTC