A simple file-comparison utility. : file utilities « File Stream « C++ Tutorial






#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) {
    cout << "Usage: compfiles <file1> <file2>\n";
    return 1;
  }

  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;
  }

  do {
    f1.read((char *) buf1, sizeof buf1);
    f2.read((char *) buf2, sizeof buf2);

    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(f1.gcount() != f2.gcount()) {
     cout << "Files are different lengths.\n";
     equal = false;
     break;
   }

   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";

 f1.clear();
 f2.clear();

 f1.close();
 f2.close();

 if(!f1.good() || !f2.good()) {
   cout << "Error closing files.\n";
   return 1;
 }

 return 0;
}








12.7.file utilities
12.7.1.Use ifstream and ofstream to copy file
12.7.2.Check file status
12.7.3.Obtaining file size
12.7.4.A file comparision utility.
12.7.5.Get file information: size, device, creation time and last modification time
12.7.6.Count number of lines of all files passed as argument
12.7.7.Copying one file into another:
12.7.8.A simple file-comparison utility.