现在的位置: 首页 > 综合 > 正文

VCL类学习之(十一) THandleStream

2017年12月01日 ⁄ 综合 ⁄ 共 1848字 ⁄ 字号 评论关闭

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.

  1. { THandleStream class }
  2.   THandleStream = class(TStream)
  3.   protected
  4.     FHandle: Integer;
  5.     procedure SetSize(NewSize: Longint); override;
  6.     procedure SetSize(const NewSize: Int64); override;
  7.   public
  8.     constructor Create(AHandle: Integer);
  9.     function Read(var Buffer; Count: Longint): Longint; override;
  10.     function Write(const Buffer; Count: Longint): Longint; override;
  11.     function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
  12.     property Handle: Integer read FHandle;
  13.   end;
  14. { THandleStream }
  15. constructor THandleStream.Create(AHandle: Integer);
  16. begin
  17.   inherited Create;
  18.   FHandle := AHandle;
  19. end;
  20. function THandleStream.Read(var Buffer; Count: Longint): Longint;
  21. begin
  22.   Result := FileRead(FHandle, Buffer, Count);
  23.   if Result = -1 then Result := 0;
  24. end;
  25. function THandleStream.Write(const Buffer; Count: Longint): Longint;
  26. begin
  27.   Result := FileWrite(FHandle, Buffer, Count);
  28.   if Result = -1 then Result := 0;
  29. end;
  30. function THandleStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
  31. begin
  32.   Result := FileSeek(FHandle, Offset, Ord(Origin));
  33. end;
  34. procedure THandleStream.SetSize(NewSize: Longint);
  35. begin
  36.   SetSize(Int64(NewSize));
  37. end;
  38. procedure THandleStream.SetSize(const NewSize: Int64);
  39. begin
  40.   Seek(NewSize, soBeginning);
  41. {$IFDEF MSWINDOWS}
  42.   Win32Check(SetEndOfFile(FHandle));
  43. {$ELSE}
  44.   if ftruncate(FHandle, Position) = -1 then
  45.     raise EStreamError(sStreamSetSize);
  46. {$ENDIF}
  47. end;

抱歉!评论已关闭.