gpt4 book ai didi

delphi - delphi 用 TFileStream 读取行

转载 作者:行者123 更新时间:2023-12-02 17:11:39 29 4
gpt4 key购买 nike

如何使用某些行读取文件 TFileStream.我阅读了包含数百万个文件的行。所以我想在我只会使用的内存中播放

示例:

Line 1: 00 00 00 00 00 00 00 00
Line 2: 00 00 00 00 00 00 00 00
Line 3: 00 00 00 00 00 00 00 00
Line 4: 00 00 00 00 00 00 00 00
Line 5: 00 00 00 00 00 00 00 00

我读了第 2 到 4 行

我使用了一个函数TextFile,但它似乎很慢。刚刚找到一个读取 TFileStream 中最后一行的函数。

最佳答案

您可以使用 TFileStream 类打开文件进行读取,如下所示...

FileStream := TFileStream.Create( 'MyBigTextFile.txt', fmOpenRead)

TFileStream 不是引用计数对象,因此请务必在完成后释放它,就像这样......

FileStream.Free

从现在开始,我将假设您的文件的字符编码是 UTF-8,并且行尾终止符是 MS 样式。如果没有,请相应调整,或​​更新您的问题。

您可以读取 UTF-8 字符的单个代码单元(与读取单个字符不同),如下所示:

var ch: ansichar;
FileStream.ReadBuffer( ch, 1);

您可以像这样阅读一行文本...

function ReadLine( var Stream: TStream; var Line: string): boolean;
var
RawLine: UTF8String;
ch: AnsiChar;
begin
result := False;
ch := #0;
while (Stream.Read( ch, 1) = 1) and (ch <> #13) do
begin
result := True;
RawLine := RawLine + ch
end;
Line := RawLine;
if ch = #13 then
begin
result := True;
if (Stream.Read( ch, 1) = 1) and (ch <> #10) then
Stream.Seek(-1, soCurrent) // unread it if not LF character.
end
end;

读取第 2、3 和 4 行,假设位置为 0 ...

ReadLine( Stream, Line1);
ReadLine( Stream, Line2);
ReadLine( Stream, Line3);
ReadLine( Stream, Line4);

关于delphi - delphi 用 TFileStream 读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11597634/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com