Seek
這篇筆記的起因是為了要 快速讀出 一個 700M 的純文字檔的最後一行,適用 Delphi7。
方法一:
以開純文字檔的方式,一次讀一行,循序讀到最後一行大約耗時 10 秒,還可接受。
- procedure TForm1.BitBtn1Click(Sender: TObject);
- var
- myfile: TextFile;
- s: string;
- begin
- memo1.clear;
- memo1.Lines.Add('start: '+FormatDateTime('yyyy-mm-dd hh:nn:ss', now));
- AssignFile(myfile, 'demo.txt');
- Reset(myfile);
- while not EOF(myfile) do
- begin
- ReadLn(myfile,s);
- end;
- memo1.Lines.Add(s);
- CloseFile(myfile);
- memo1.Lines.Add('stop: '+FormatDateTime('yyyy-mm-dd hh:nn:ss', now));
- end;
方法二:
在確定特定檔案格式的前提開啟檔案,可透過 seek 指令,將檔案指標移到指定位置。
- procedure TForm1.btnSeekClick(Sender: TObject);
- var
- myWord: char;
- myFile : File of char; // 檔案為字元格式
- iPos: Longint;
- str: string;
- begin
- memo1.Clear;
- // 以唯讀模式開啟檔案
- AssignFile(myFile, 'demo.txt');
- Reset(myFile);
- // 取得檔案最末 50 個字元的文字指標位置
- iPos := FileSize(myfile) - 50;
- // 直接移動文字指標目的地
- Seek(myFile, iPos);
- // 一次讀一個字元, 並存入 str, 直至檔案末
- while not EOF(myfile) do
- begin
- Read(myFile, myWord);
- str := str + myWord;
- Inc(iPos);
- Seek(myFile, iPos);
- end;
- memo1.Lines.Add(str);
- // 關閉檔案
- CloseFile(myFile);
- end;