Hi , i have 2 txt files full of names , read line by line and compare. If name from first file exist in second , i don't write it to result file. My code work excelent with small files , but when i try big files (100 MB) , the program is very slow. My friend advise me to use array, but i have problem with coding. Any other ideas is also welcome. Thank you in advance for your help and sorry for bad english , not native for me ! This is code i use:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main()
{

ifstream ifs1("data1.txt");
vector<string> data1;
if (ifs1.is_open()){
string line;
while(getline(ifs1, line)){
data1.push_back(line);
}
}
else{
cout << "Unable to open file data1.txt";
return 1;
}

ifstream ifs2("data2.txt");
if (ifs2.is_open()){
string line;
while(getline(ifs2, line)){
for(size_t i = 0; i < data1.size(); ++i){
if (line == data1)
data1.erase(data1.begin()+i);
}
}
}
else{
cout << "Unable to open file data2.txt";
return 1;
}
ofstream ofs("result.txt");
if (ofs.is_open()){
for(size_t i = 0; i < data1.size(); ++i){
ofs << data1 << endl;
}
}
else{
cout << "Unable to open file result.txt";
return 1;
}
return 0;
}

What you are doing is reading the first file and then reading the seconds file. Read both the files at the same time.

Read both files at the same time as firstPerson mentioned, then compare the lines as they are read; no need to put them in a vector unless you intend to do something else with them.

sorry for stupid question , but how to read two files at same time ?

sorry for stupid question , but how to read two files at same time ?

You already know how to.

//open file1
//open fil2

while( file1 >> string1 && file2 >> string2 ){
   //compare string and do logic here
}

Now if they are different length then you have to do something a
little extra.

i try this , but code only read and write first line of first line , don't compare

int main()
{

ifstream ifs1("data1.txt"); //file1
ifstream ifs2("data2.txt"); //file2
ofstream ofs("result.txt");
string line1;
string line2;
while( ifs1 >> line1 && ifs2 >> line2){
    if (line1.compare(line2)!= 0)
        ofs <<line1<< endl;


}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.