C++ Program to Compare Two Files for Identical Content
Here's a C++ program that reads two files and checks if they are identical copies:
#include <iostream>
#include <fstream>
#include <sstream>
bool compareFiles(const std::string& filename1, const std::string& filename2) {
std::ifstream file1(filename1);
std::ifstream file2(filename2);
if (!file1 || !file2) {
std::cout << "Error opening files!" << std::endl;
return false;
}
std::stringstream buffer1, buffer2;
buffer1 << file1.rdbuf();
buffer2 << file2.rdbuf();
return buffer1.str() == buffer2.str();
}
int main() {
std::string filename1, filename2;
std::cout << "Enter filename 1: ";
std::cin >> filename1;
std::cout << "Enter filename 2: ";
std::cin >> filename2;
if (compareFiles(filename1, filename2)) {
std::cout << "The files are identical copies." << std::endl;
} else {
std::cout << "The files are not identical." << std::endl;
}
return 0;
}
In this program, we define a compareFiles function that takes two filenames as input. It attempts to open the files, and if successful, it uses stringstreams to read the contents of each file. Finally, it compares the contents of the two stringstreams and returns true if they are identical.
In the main function, we prompt the user to enter the filenames of the two files they want to compare. We then call the compareFiles function with the provided filenames and display an appropriate message based on the result.
Note: Make sure the two files you want to compare are in the same directory as the program, or provide the full path to the files.
原文地址: https://www.cveoy.top/t/topic/o1Sw 著作权归作者所有。请勿转载和采集!