/* Matt Mahoney, mmahoney@cs.fit.edu compare.cpp is a program to compare two text files. To run, specify the two file names on the command line: compare file1 file2 The possible outcomes are: Usage: compare file1 file2 (If there are not 2 arguments) file1 not found (Whether or not file2 exists) file2 not found (If file1 exists) file1 and file2 are identical (Files match exactly) file1 and file2 differ on line N (Only the first differing line file1: contents of line N is shown. N = 1, 2, 3...) file2: contents of line N file1 continues past end of file2 (If the files are identical up to the end of the shorter one, file2 continues past end of file1 but one file continues on) For example: file1: file2: file3: this is this this a test is a test compare Usage: compare file1 file2 compare file1 file2 file1 and file2 differ on line 1 file1: this is file2: this compare file2 file3 file2 continues past end of file3 compare file1 file1 file1 and file1 are identical compare foo bar foo not found */ #include #include #include using namespace std; int main(int argc, char** argv) { // Test for 2 arguments: compare file1 file2 if (argc!=3) { cout << "Usage: compare file1 file2\n"; return 1; } // Open, test file1 ifstream f1(argv[1]); if (!f1) { cout << argv[1] << " not found\n"; return 1; } // Open, test file2 ifstream f2(argv[2]); if (!f2) { cout << argv[2] << " not found\n"; return 1; } // Compare line by line until a mismatch is found or until either file ends string s1, s2; // Lines of file1 and file2 int lines=0; // Count while (true) { getline(f1, s1); getline(f2, s2); if (!f1 || !f2) break; ++lines; if (s1 != s2) { cout << argv[1] << " and " << argv[2] << " differ on line " << lines << "\n" << argv[1] << ": " << s1 << "\n" << argv[2] << ": " << s2 << "\n"; return 0; } } // Test for different lengths if (f1) cout << argv[1] << " continues past end of " << argv[2] << "\n"; else if (f2) cout << argv[2] << " continues past end of " << argv[1] << "\n"; else cout << argv[1] << " and " << argv[2] << " are identical\n"; return 0; }