Create a file comparision utility. : File Utility « File « C++






Create a file comparision utility.

 


   
#include <iostream>  
#include <fstream>  
using namespace std;  
  
int main(int argc, char *argv[])  
{  
  register int i;  
  int numread;  
  
  unsigned char buffer1[1024], buffer2[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 first file.\n";  
    return 1;  
  }  
  ifstream f2(argv[2], ios::in | ios::binary);  
  if(!f2) {  
    cout << "Cannot open second file.\n";  
    return 1;  
   }  
  
  cout << "Comparing files...\n";  
  
  do {  
    f1.read((char *) buffer1, sizeof buffer1);  
    f2.read((char *) buffer2, sizeof buffer2);  
 
    if(f1.gcount() != f2.gcount()) { 
      cout << "Files are of differing sizes.\n"; 
      f1.close();  
      f2.close();  
      return 0; 
    } 
    
    for(i = 0; i <f1.gcount(); i++)  // compare contents of buffers  
      if(buffer1[i] != buffer2[i]) {  
        cout << "Files differ.\n";  
        f1.close();  
        f2.close();  
        return 0;  
      }  
  
  } while(!f1.eof() && !f2.eof());  
  
  cout << "Files are the same.\n";  
  
  f1.close();  
  f2.close();  
  
  return 0;  
}


           
         
  








Related examples in the same category

1.Read and display a text file line by line.
2.Display contents of specified file in both ASCII and in hex.
3.Copy a text file and display number of chars copied.
4.Word count for input file: file read with ifstream
5.Copy files
6.Copy a file and display number of chars copied.
7.Concatenate files
8.Swap characters in a file.
9.Swap characters in a file with error checking.
10.Copy a file and reverse case of letters.
11.Count letters.
12.Copy a file and reverse case of letters with error checking.
13.Copy and convert tabs to spaces.
14.Search file.