我有一些代码合并了两个文本文件(第一个和第二个)。如何检查第一个文件的内容是否在第二个文件内并跳过合并?
[Code]
procedure AppendFile(const SrcFile, DestFile: string);
var
SrcStream: TFileStream;
DestStream: TFileStream;
begin
SrcStream := TFileStream.Create(SrcFile, fmOpenRead);
try
DestStream := TFileStream.Create(DestFile, fmOpenWrite);
try
DestStream.Seek(0, soFromEnd);
DestStream.CopyFrom(SrcStream, SrcStream.Size);
finally
DestStream.Free;
end;
finally
SrcStream.Free;
end;
end;
答案 0 :(得分:1)
最简单的Unicode安全实现是使用TStringList
class:
function NeedAppend(const SrcFile, DestFile: string): Boolean;
var
SrcContents: TStringList;
DestContents: TStringList;
begin
SrcContents := TStringList.Create();
DestContents := TStringList.Create();
try
SrcContents.LoadFromFile(SrcFile);
DestContents.LoadFromFile(DestFile);
Result := (Pos(SrcContents.Text, DestContents.Text) = 0);
finally
SrcContents.Free;
DestContents.Free;
end;
if not Result then
begin
Log('Contents present already, will not append');
end
else
begin
Log('Contents not present, will append');
end;
end;
虽然效率不高,但文件很大。
一旦你以这种方式实现了差异,你可以将它与合并这个简单的代码结合起来:
procedure AppendFileIfNeeded(const SrcFile, DestFile: string);
var
SrcContents: TStringList;
DestContents: TStringList;
begin
SrcContents := TStringList.Create();
DestContents := TStringList.Create();
try
SrcContents.LoadFromFile(SrcFile);
DestContents.LoadFromFile(DestFile);
if Pos(SrcContents.Text, DestContents.Text) > 0 then
begin
Log('Contents present already, will not append');
end
else
begin
Log('Contents not present, will append');
DestContents.AddStrings(SrcContents);
DestContents.SaveToFile(DestFile);
end;
finally
SrcContents.Free;
DestContents.Free;
end;
end;