Interesting Problem with multiple File I/O

I am experiencing a problem reading in from files.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
myfile1.open("File1");
if (myfile5.is_open())
{
	while(!myfile1.eof())
	{
		myfile1>>var1;
		myfile2.open("File2");
		while (!myfile2.eof())
		{	
			myfile2>>var2;
			if (var1==var2)
				Do Something...
		}
		myfile2.close();
		myfile2.clear();
	}
}
myfile1.close();


The error is that the inner while loop executes only once! instead of executing until file1.eof()

Memory is an issue so loading either of the list is not possible.

Thank you for your comments!

It looks like a design problem with so many open files.
Also, you should not be looping on EOF.

What exactly is it you are trying to do? Perhaps we can suggest a better way...
Perhaps myfile2 is not opening? I don't know what would happen with the while(!myfile2.eof()) but if you haven't looked could be worthwhile.
Thanks for the feedback.

The piece of code seems to work now!

The objective of the program is to read from two input files and do some comparisons on them.
I did the EOF loop since i had to read every thing from the file and the number of tokens coming in were unknown.

What would be a better way to achieve this?

Thanks! :)
1
2
3
4
5
6
7
8
9
10
std::ifstream first("file1.txt");
std::ifstream second("file2.txt");

int a, b;
if(first.is_open() && second.is_open()) {
    while(first >> a && second >> b) {
        if(a == b) // ...
    }
}
// don't call close; let first and second fall out of scope 

Also notice your variable names are prone to confusion and non descriptive. Try to use better names (the ones I used are terrible as well, but at least they're clearly different).
Thank you filipe

But this approach would not work since I am comparing each element of file1 with all the elements of file2.
So may be something like this could work.

1
2
3
4
5
6
7
8
9
10
11
12
std::ifstream first("file1.txt");
std::ifstream second("file2.txt");

int a, b;
if(first.is_open()) 
{
        while (first >> a) {
                  while (first >> b) {
                               if(a == b) // ...
                  }
    }
}


Note: Variable names are shown for demonstration purposes. Not actual variable names used in the program.
Ah, I misread the snippet you had posted. But you certainly got the idea. Just remember to check whether second is open too.

PS: when posting here, prefer spaces (I use 4) to tabs because tabs are 8 spaces by default and too much indentation can hurt readability a bit.
Yep. I just noticed that.
Thank you :)
Topic archived. No new replies allowed.