Compare two files of txt format

Posted in Algorithms

We will read strings from each file while each of files has a data. And we will compare each string from the first file with corresponding string from the second file. All differences we will write in a memo.

procedure TForm1.Button1Click(Sender: TObject);
var
  First, Second: TextFile;
  Str, Str2: string;
begin
  Memo1.Clear;
  if (Edit1.Text<>'')and(Edit2.Text<>'') then
  begin
    AssignFile(First, Edit1.Text);
    AssignFile(Second, Edit2.Text);
    Reset(First);
    Reset(Second);
    while not EOF(First) do
    begin
      if EOF(Second)=True then
      begin
        Memo1.Lines.Add('*** ATTENTION ***');
        Memo1.Lines.Add('SECOND file has finished
                         but FIRST file has had a data yet.');
        Break;
      end;
      Readln(First, Str);
      Readln(Second, Str2);
      if CompareStr(Str, Str2)<>0 then
      begin
        Memo1.Lines.Add('FIRST  - '+Str);
        Memo1.Lines.Add('SECOND - '+Str2);
        Memo1.Lines.Add(' ');
      end;
    end;
    if EOF(Second)=False then
    begin
      Memo1.Lines.Add('*** ATTENTION ***');
      Memo1.Lines.Add('FIRST file has finished
                       but SECOND file has had a data yet.');
    end;
    CloseFile(First);
    CloseFile(Second);
    if Memo1.Lines.Count=0 then
      Memo1.Lines.Add('FIRST file is identical to SECOND file');
  end;
end;