EncodStr.pas
Upload User: fh681027
Upload Date: 2022-07-23
Package Size: 1959k
Code Size: 2k
Category:

Delphi VCL

Development Platform:

Delphi

  1. unit EncodStr;
  2. interface
  3. uses
  4.   Classes;
  5. type
  6.   TEncodedStream = class (TFileStream)
  7.   private
  8.     FKey: Char;
  9.   public
  10.     constructor Create(const FileName: string; Mode: Word);
  11.     function Read(var Buffer; Count: Longint): Longint; override;
  12.     function Write(const Buffer; Count: Longint): Longint; override;
  13.     property Key: Char read FKey write FKey default 'A';
  14.   end;
  15. implementation
  16. constructor TEncodedStream.Create(
  17.   const FileName: string; Mode: Word);
  18. begin
  19.   inherited Create (FileName, Mode);
  20.   FKey := 'A';
  21. end;
  22. function TEncodedStream.Write(const Buffer; 
  23.   Count: Longint): Longint;
  24. var
  25.   pBuf, pEnc: PChar;
  26.   I, EncVal: Integer;
  27. begin
  28.   // allocate memory for the encoded buffer
  29.   GetMem (pEnc, Count);
  30.   try
  31.     // use the buffer as an array of characters
  32.     pBuf := PChar (@Buffer);
  33.     // for every character of the buffer
  34.     for I := 0 to Count - 1 do
  35.     begin
  36.       // encode the value and store it
  37.       EncVal := ( Ord (pBuf[I]) + Ord(Key) ) mod 256;
  38.       pEnc [I] := Chr (EncVal);
  39.     end;
  40.     // write the encoded buffer to the file
  41.     Result := inherited Write (pEnc^, Count);
  42.   finally
  43.     FreeMem (pEnc, Count);
  44.   end;
  45. end;
  46. function TEncodedStream.Read(var Buffer; Count: Longint): Longint;
  47. var
  48.   pBuf, pEnc: PChar;
  49.   I, CountRead, EncVal: Integer;
  50. begin
  51.   // allocate memory for the encoded buffer
  52.   GetMem (pEnc, Count);
  53.   try
  54.     // read the encoded buffer from the file
  55.     CountRead := inherited Read (pEnc^, Count);
  56.     // use the output buffer as a string
  57.     pBuf := PChar (@Buffer);
  58.     // for every character actually read
  59.     for I := 0 to CountRead - 1 do
  60.     begin
  61.       // decode the value and store it
  62.       EncVal := ( Ord (pEnc[I]) - Ord(Key) ) mod 256;
  63.       pBuf [I] := Chr (EncVal);
  64.     end;
  65.   finally
  66.     FreeMem (pEnc, Count);
  67.   end;
  68.   // return the number of characters read
  69.   Result := CountRead;
  70. end;
  71. end.