我试图找到mykeyword
的位置并从加载的文件中提取字符串(最多200 MB)。
procedure TForm5.Button4Click(Sender: TObject);
var
Stream: TFileStream;
Buffer: array [0 .. 1023] of AnsiChar;
i: Integer;
myKeyword: string;
pullStr: AnsiString;
begin
myKeyword :='anything';
Stream := TFileStream.Create(edtTarget.Text, fmOpenRead);
while Stream.Position < Stream.Size do
begin
Stream.Read(Buffer, 1024);
m1.Lines.Add(Buffer); // no need, just display to evaluate
(* 1. Get address of given keyword *)
// i := Stream.PositionOf(myKeyword); < how to do this?
(* 2. Stream Exract *)
// pullStr := Stream.copy(i,1000); < how to do this ?
end;
end;
我已阅读有关文件和字符串的其他主题。我找到了一个非常好的答案from here。我想我想扩展这些功能。 像
这样的东西TFileSearchReplace.GetStrPos(const KeyWord: string) : Integer;
TFileSearchReplace.ExtractStr (const KeyWord: string; Len : Integer) ;
答案 0 :(得分:1)
procedure TForm5.Button4Click(Sender: TObject);
var
Stream: TFileStream;
Buffer: AnsiString;
i, BytesRead, SearchPos: Integer;
myKeyword: string;
pullStr: AnsiString;
Found: Boolean;
begin
myKeyword :='anything';
Found := False;
SetLength(Buffer, 1024);
Stream := TFileStream.Create(edtTarget.Text, fmOpenRead);
while Stream.Position < Stream.Size do
begin
// read some bytes and remember, how many bytes been read actually
BytesRead := Stream.Read(Buffer[1], 1024);
// glue new bytes to the end of the pullStr
pullStr := pullStr + copy(Buffer, 1, BytesRead);
// file is divided to two parts: before myKeyword, and after
// if myKeyword alreay found, there is nothing to do, just repeat reading to pullStr
if Found then
continue;
// if myKeyword is not found yet, pullStr acts like temporary buffer
// search for myKeyword in buffer
SearchPos := Pos(myKeyword, pullStr);
if SearchPos > 0 then
begin //keyword was found, delete from beginning up to and icluding myKeyword
// from now on, pullStr is not tmp buffer, but result
Found := True;
Delete(pullStr, 1, SearchPos + Length(myKeyWord) - 1);
continue;
end;
// myKeyword still not found. Find last line end in buffer
SearchPos := LastDelimiter(#13#10, pullStr);
// and delete everything before it
if SearchPos > 0 then
Delete(pullStr, 1, SearchPos);
// so if myKeyword spans across two reads, it still will be found in next iteration
end;
// if there is no myKeyword in file, clear buffer
if not Found then
pullStr := '';
end;