Compare two files

image_pdfimage_print
   

/*
C# A Beginner's Guide
By Schildt

Publisher: Osborne McGraw-Hill
ISBN: 0072133295
*/
/*   
   Project 11-1 
 
   Compare two files. 
 
   To use this program, specify the names   
   of the files to be compared on the command line. 
 
   For example: 
       CompFile FIRST.TXT SECOND.TXT  
*/  
  
using System; 
using System.IO;  
  
public class CompFiles {  
  public static void Main(string[] args) {  
    int i=0, j=0;  
    FileStream f1;  
    FileStream f2;  
  
    try {  
      // open first file 
      try {  
        f1 = new FileStream(args[0], FileMode.Open);  
      } catch(FileNotFoundException exc) {  
        Console.WriteLine(exc.Message);  
        return;  
      }  
  
      // open second file  
      try {  
        f2 = new FileStream(args[1], FileMode.Open);  
      } catch(FileNotFoundException exc) {  
        Console.WriteLine(exc.Message);  
        return;  
      }  
    } catch(IndexOutOfRangeException exc) {  
      Console.WriteLine(exc.Message + "
Usage: CompFile f1 f2");  
      return;  
    }  
  
    // Compare files  
    try {  
      do {  
        i = f1.ReadByte();  
        j = f2.ReadByte();  
        if(i != j) break; 
      } while(i != -1 && j != -1);  
    } catch(IOException exc) {  
      Console.WriteLine(exc.Message);  
    }  
    if(i != j)  
      Console.WriteLine("Files differ."); 
    else 
      Console.WriteLine("Files are the same."); 
  
    f1.Close();  
    f2.Close();  
  }  
}



           
          


This entry was posted in File Stream. Bookmark the permalink.