Search code examples
delphistring-comparisondelphi-10.3-rio

How check what lines are equal in two text files?


This simply code is working fine to check if lines are different, already when i try check if are equals none element is found when have two files with the same string in same line index on both. What is missing here?

PS: SameStr() also was tested and not is working.

function compstr(s1, s2: string): boolean;
var
  i: integer;
  btemp: boolean;
begin
  btemp := true;
  if (length(s1) <> length(s2)) then
  begin
    btemp := false;
  end
  else
  begin
    for i := 1 to length(s1) do
    begin
      if (s1[i] <> s2[i]) then
      begin
        btemp := false;
        exit;
      end;
    end;
  end;
  result := btemp;
end;

procedure compfile(filename1, filename2: string);
var
  f1: system.textfile;
  f2: system.textfile;
  diff: system.textfile;
  buf1: string;
  buf2: string;
  l: integer;
begin
  assignfile(f1, filename1);
  assignfile(f2, filename2);
  assignfile(diff, 'C:\Equals.txt');
  reset(f1);
  reset(f2);
  rewrite(diff);
  l := 1;
  while not eof(f1) do
  begin
    readln(f1, buf1);
    readln(f2, buf2);
    if {not} compstr(buf1, buf2) then
    begin
      writeln(diff, {extractfilename(filename1) + ' : ' +} inttostr(l) + ' - ' + buf1);
     // writeln(diff, extractfilename(filename2) + ' : ' + inttostr(l) + ' - ' + buf2);
     // writeln(diff, ' ');
    end;
    inc(l);
  end;
  closefile(f1);
  closefile(f2);
  closefile(diff);
end;

Solution

  • Your function compstr(s1, s2: string): boolean; has a couple of issues:

    1. The btemp: boolean variable is unnecessary. You can set result directly as needed.

    2. If the length of the two lines are equal, but the content differs (if (s1[i] <> s2[i])) you call exit which jumps to the end; of the function and result is never assigned the value of btemp. Thus, strings of equal length but different content are returning the value True, that you set at the beginning. Perhaps you were thinking about break which would exit the for loop and land on the result := btemp; line, which then would yield the correct value.

    3. The whole function is a waste, you call it it in compfile() with:

       ...
       if compstr(buf1, buf2) then
       ....
    

    which can be replaced with direct comparison:

       ....
       if buf1 = buf2 then
       ....
    

    P.S. Your claim that SameStr() is not working is false. You probably did not use it correctly.