2008. március 21., péntek

Rewrite the last line of text in a text file


Problem/Question/Abstract:

How to rewrite the last line of text in a text file

Answer:

procedure RewriteLastTextLine(AFileName: string; ANewTextLine: string);
const
  BUFFER_SIZE = 1024; {change this number for different sized buffer}
  CRLF = #13#10;
var
  fs: TFileStream;
  buf: PChar;
  iStartWritePos: Int64;

  function AssignPos: Boolean;
  var
    i: Integer;
  begin
    for i := BUFFER_SIZE - 1 downto 0 do
      if (buf[i] = #13) then
      begin
        iStartWritePos := (iStartWritePos - (BUFFER_SIZE - i));
        Result := True;
        Exit;
      end;
    Result := False;
  end;

  procedure ReadABuffer;
  begin
    fs.Position := fs.Position - BUFFER_SIZE;
    fs.Read(buf^, BUFFER_SIZE);
    fs.Position := fs.Position - BUFFER_SIZE;
  end;

begin
  fs := TFileStream.Create(AFileName, fmOpenReadWrite or fmShareDenyWrite);
  try
    GetMem(buf, BUFFER_SIZE);
    FillMemory(buf, BUFFER_SIZE, 0);
    fs.Position := fs.Size;
    iStartWritePos := fs.Position;
    repeat
      ReadABuffer
    until
      AssignPos;
    fs.Position := iStartWritePos;
    fs.Write(CRLF, Length(CRLF));
    fs.Write(ANewTextLine[1], Length(ANewTextLine));
  finally
    FreeMem(buf, BUFFER_SIZE);
    fs.Free;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése