C++ examples for File Stream:File Operation
Simple File-Comparison Utility
#include <iostream> #include <fstream> using namespace std; int main(int argc, char *argv[]) { bool equal = true; bool ferr = false; unsigned char buf1[1024], buf2[1024]; if(argc!=3) {//w w w . j ava 2 s.c om cout << "Usage: compfiles <file1> <file2>\n"; return 1; } // Open both files for binary operations. ifstream f1(argv[1], ios::in | ios::binary); if(!f1) { cout << "Cannot open " << argv[1] << endl; return 1; } ifstream f2(argv[2], ios::in | ios::binary); if(!f2) { cout << "Cannot open " << argv[2] << endl; f1.close(); if(!f1.good()) cout << "Error closing " << argv[1] << endl; return 1; } cout << "Comparing files...\n"; do { // Read a buffer full of data from both files. f1.read((char *) buf1, sizeof buf1); f2.read((char *) buf2, sizeof buf2); // Check for read errors. if(!f1.eof() && !f1.good()) { cout << "Error reading " << argv[1] << endl; ferr = true; break; } if(!f2.eof() && !f2.good()) { cout << "Error reading " << argv[2] << endl; ferr = true; break; } // If the two files differ in length, then at the // end of the file, the gcounts will be different. if(f1.gcount() != f2.gcount()) { cout << "Files are different lengths.\n"; equal = false; break; } // Compare contents of buffers. for(int i=0; i < f1.gcount(); ++i) if(buf1[i] != buf2[i]) { cout << "Files differ.\n"; equal = false; break; } } while(!f1.eof() && !f2.eof() && equal); if(!ferr && equal) cout << "Files are the same.\n"; // Clear eofbit, and possibly error bits. f1.clear(); f2.clear(); f1.close(); f2.close(); if(!f1.good() || !f2.good()) { cout << "Error closing files.\n"; return 1; } return 0; }