2010年12月30日 星期四

比較兩檔案之異同

使用下列敘述呼叫它:
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 + "\nUsage: 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();
 }
}

沒有留言: