SystemFreeMem (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following example opens a file of your choice and reads the entire file into a dynamically allocated buffer. The buffer and the size of the file are then passed to a routine that processes the text, and finally the dynamically allocated buffer is freed and the file is closed.

Code

procedure TForm1.Button1Click(Sender: TObject);
var
  F: file;
  Size: Integer;
  Buffer: PAnsiChar;
begin
  if OpenDialog1.Execute then
  begin
    AssignFile(F, OpenDialog1.FileName);
    Reset(F, 1);
    try
      Size := FileSize(F);
      GetMem(Buffer, Size);
      try
        BlockRead(F, Buffer^, Size);
        Memo1.Lines.Add(AnsiString(Buffer));
      finally
        FreeMem(Buffer);
      end;
    finally
      CloseFile(F);
    end;
  end;
end;
Note: System.BlockRead should be used with great care because the untyped parameter (Buffer) can be the source of memory corruption. To avoid this, it is preferable to use streams.

Uses

Personal tools
Assistance