Hi,

I am comparing two file to find if they have common strings. My program is not doing that and I cannot figure out the reason. Any help is appreciated. Following is my code:

int main()
{
	FILE *inf1 = fopen("file1.txt","r");
	FILE *inf2 = fopen("file2.txt","r");
	int numcols = 11;
	char line1[numcols], line2[numcols];

	while(fgets(line1, (numcols+1), inf1))
	{
		while(fgets(line2, (numcols+1), inf2))
		{
			if(line1 == line2)
			{
				cout << "Found a matching line" << "line1 = " << line1 << endl;
				break;
			}
		}
		rewind(inf2);
	}
	return 0;
}

Following are my file1.txt and file2.txt

file1.txt
---------------
1 0 2 2 0 1
1 1 2 2 1 1

file2.txt
-------------
0 0 0 0 0 0
0 0 0 0 0 1
1 0 2 2 0 1
1 1 2 2 1 1

Thanks

Dani AI

Generated

Two separate problems are stopping the program from finding matching lines.

First, line1 == line2 does not compare the contents of the C-style arrays; it compares their addresses. pointed this out correctly. Second, the declarations and fgets call are unsafe: char line1[numcols] with fgets(..., numcols+1, ...) overruns the buffer, and variable-length arrays (char buf[n] with non-constant n) are not standard C++ (as hinted) so the code may not compile portably. Also remember fgets keeps the trailing newline, so raw string comparisons can fail because of that.

A simple, robust fix is to use C++ streams and std::string. Read one file into a hash set and then check each line of the other file for membership — this avoids nested loops and makes comparisons straightforward:

#include <fstream>
#include <iostream>
#include <string>
#include <unordered_set>

int main() {
    std::ifstream f1("file1.txt"), f2("file2.txt");
    if (!f1 || !f2) return 1;
    std::unordered_set<std::string> s;
    std::string line;
    while (std::getline(f2, line)) s.insert(line);
    while (std::getline(f1, line)) {
        if (s.find(line) != s.end())
            std::cout << "Found matching line: " << line << '\n';
    }
}

Notes: if whitespace differences matter (extra spaces, different spacing between numbers) normalize lines (tokenize and compare number sequences) before inserting/searching. If you must stick to C APIs, use a correctly sized buffer, remove the trailing newline before comparing, and call strcmp() for content comparison. For std::getline and std::unordered_set details see std::getline and std::unordered_set.

Recommended Answers

All 2 Replies

>>int numcols = 11;
>> char line1[numcols], line2[numcols];

Does that even compile for you ?

Assuming you can get it to compile, your string comparison in:
if(line1 == line2)
is actually comparing the addresses of line1 and line2, not the array contents.
Try using string objects to store the lines, or use an array comparison method such as strcmp().

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.