1755266 Members
5054 Online
108831 Solutions
New Discussion юеВ

Re: C++ Filestream

 
Tnameh
Occasional Advisor

C++ Filestream

I have to implement routine in C++ using fstream.

Which wll take compare two file lets say Input1 and Input2.
It wll delete contents of Input1 from Input2 files.

Can somebody suggest me a better idea of doing it, using fstream

Input1 File
Hello how are you I am fine.
C++ world.
People in This forum is great.


Input 2 file
I am doing fine
Wishing u all the best.
Hello how are you I am fine.
C++ world.
People in This forum is great.
Thanks for this program


When i run binary the contents of the file Input2 should be like

Input2 file
I am doing fine
Wishing u all the best.
Thanks for this program
4 REPLIES 4
Dennis Handly
Acclaimed Contributor

Re: C++ Filestream

Note: There is no reason to use fstream, you should use stdio.

In general, if the files aren't sorted, you'll need to keep file1 in memory so you don't need to re-read file1 for each line in file2. You would then sort file1 and when reading file2, use a binary search to see if in file1.

Alternately, you can add a new field to file2, containing the original order, sort it and file1 and then read the records, removing duplicates. Then re-sort file2, and remove the extra field.
Leonardo_14
Frequent Advisor

Re: C++ Filestream

// try it
// here is the code

#include
#include
#include



fstream fp1;
fstream fp2;
fstream temp;
boolean line_to_print=true;

string str_line_fp1;
string str_line_fp2;


fp1.open ("Input1_File", fstream::out);
fp2.open ("Input2_File", fstream::out);
temp.open ("tempFile", fstream::in);

while (fp2.good()) {

fp2 >> str_line_fp2;

while (fp1.good()) {

fp1 >> str_line_fp1;

// check if linefile2 is in file1
if (str_line_fp2 == str_line_fp1)

line_to_print=false;


} //end wihle fp1

if (line_to_print == true) {

temp << str_line_fp2;
temp.flush();

}

line_to_print=true;


} //end wihle fp2

rename ("tempFile", "Input2_File");

// end
Leonardo_14
Frequent Advisor

Re: C++ Filestream

so you have to close files so as explained in the attachment file

Ciauz ;)
Dennis Handly
Acclaimed Contributor

Re: C++ Filestream

> so you have to close files

Several problems with your fragment. You are using fstream vs stdio. :-)

You open each file in the wrong mode. You should NOT be calling flush, instead insert a '\n'. Replace boolean by bool. You need to call getline vs the string extracter. And you should be calling pubseekoff and clear to rewind fp1.

See attached.