THandleStream enables applications to read from and write to communications resources identified by a handle.
Unit
Classes
Description
Use THandleStream to access files, sockets, named pipes, mailslots, or other communications resources that provide a handle when opened. For example, the FileOpen function provides a handle for a file on disk. THandleStream allows applications to use a uniform stream interface when performing I/O using a handle.
To avoid the overhead of managing file handles, use TFileStream to work with disk files.
- { THandleStream class }
- THandleStream = class(TStream)
- protected
- FHandle: Integer;
- procedure SetSize(NewSize: Longint); override;
- procedure SetSize(const NewSize: Int64); override;
- public
- constructor Create(AHandle: Integer);
- function Read(var Buffer; Count: Longint): Longint; override;
- function Write(const Buffer; Count: Longint): Longint; override;
- function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
- property Handle: Integer read FHandle;
- end;
- { THandleStream }
- constructor THandleStream.Create(AHandle: Integer);
- begin
- inherited Create;
- FHandle := AHandle;
- end;
- function THandleStream.Read(var Buffer; Count: Longint): Longint;
- begin
- Result := FileRead(FHandle, Buffer, Count);
- if Result = -1 then Result := 0;
- end;
- function THandleStream.Write(const Buffer; Count: Longint): Longint;
- begin
- Result := FileWrite(FHandle, Buffer, Count);
- if Result = -1 then Result := 0;
- end;
- function THandleStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
- begin
- Result := FileSeek(FHandle, Offset, Ord(Origin));
- end;
- procedure THandleStream.SetSize(NewSize: Longint);
- begin
- SetSize(Int64(NewSize));
- end;
- procedure THandleStream.SetSize(const NewSize: Int64);
- begin
- Seek(NewSize, soBeginning);
- {$IFDEF MSWINDOWS}
- Win32Check(SetEndOfFile(FHandle));
- {$ELSE}
- if ftruncate(FHandle, Position) = -1 then
- raise EStreamError(sStreamSetSize);
- {$ENDIF}
- end;