StreamAdvancedRdWr (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of TStreamReader's ReadBlock and DiscardBufferedData methods. ReadBlock is used to read a fixed number of characters from the reader and DiscardBufferedData is used when the underlying stream is seeked manually.

Code

procedure TMainForm.Button1Click(Sender: TObject);
var
  Writer: TStreamWriter;
  Reader: TStreamReader;
  Buffer: TCharArray;
  ByteCount: Integer;
begin
  { Create a writer }
  Writer := TStreamWriter.Create('local_file.txt');

  { Dump some data in }
  Writer.WriteLine('Hello');
  Writer.WriteLine('World!');

  { Close the writer }
  Writer.Free;

  { Create a reader }
  Reader := TStreamReader.Create('local_file.txt');

  { Prepare a buffer }
  SetLength(Buffer, 5);

  { Read first 5 characters }
  if Reader.ReadBlock(Buffer, 0, Length(Buffer)) < Length(Buffer) then
    MessageDlg('Reading failed! Expected to read 5 characters!', mtError, [mbOK], 0);

  { And now, seek the stream back by 5 characters }
  ByteCount := Reader.CurrentEncoding.GetByteCount(Buffer);
  Reader.BaseStream.Seek(-1 * ByteCount, soFromCurrent);

  { Reset the internal data buffer, since we modified the stream position }
  Reader.DiscardBufferedData();

  MessageDlg('The original message was:' + Reader.ReadLine() +
    ' ' + Reader.ReadLine(), mtError, [mbOK], 0);

  Reader.Free;
end;

Uses