Title: File streaming
Question: How do I use a stream to read data from a file?
Answer:
All you have to do is create the strea, read/write from it and then free it. Here is an example for reading from a stream:
procedure TForm1.Button1Click(Sender: TObject);
var
Buffer: PChar;
Stream: TFileStream;
Size: LongInt;
begin
Stream := TFileStream.Create('Unit1.pas', fmOpenRead);
try
Size := Stream.Size;
GetMem(Buffer, Size);
try
Stream.Read(Buffer[0], Size);
Memo1.Lines.Text := Buffer;
finally
FreeMem(Buffer);
end;
finally
Stream.Free; //eventually
end;
end;
or to avoid hassling with memory management altogether:
procedure TForm1.Button2Click(Sender: TObject);
var
Buffer: string;
Stream: TFileStream;
begin
Stream := TFileStream.Create('unit1.pas', fmOpenRead);
try
SetLength(buffer, Stream.Size);
Stream.Read(Buffer[1], Stream.Size);
Memo1.Lines.Text := Buffer;
finally
Stream.Free; //eventually
end;
end;
Bogdan Grigorescu - bogdang@gmail.com
BG Remote Programming Group