Thursday, 26 April 2018

Delphi - TFileStream - Simple Example

TFileStream can be handy for looking at a file without having to actually load it into memory since it just provides a more efficient way to view it on disk. Below is a very simple example illustrating how to locate a character in a filestream:

procedure TForm1.Button1Click(Sender: TObject);
var
  FS: TFileStream; 

  X: char;  
begin
  FS := TFileStream.Create('C:\Temp\Example.txt', fmOpenRead);
  try
    FS.Position := 0;
    FS.Read(X,2);  

    ShowMessage(X);  
 finally
    FS.Free;
  end;
end;


This will create a filestream based on the information fed to the constructor, i.e. the file and the mode of operation. 

It will then set the position of the filestream to 0, i.e. what is my start point in the stream (it's 0 by default but if you wanted to alter your start point, this is how you'd do it).

It will then perform a Read on the string. It will start at the current position (in this case 0) and then read the number of bytes specified (in this case 2) and it will store these bytes in memory at a given location (in this case X). 

It will then show a message of the first character in the text file. 

Finally we free the filestream which ensures there is no memory leak.

NB, it is important to declare the X var at the start, since this will ensure that memory space is created. This space will then be used by FS.Read later to store data extracted from the filestream. In this example i have set it to be a char, since a char is 2 bytes of memory and i was just extracting the first two bytes of the stream but you could set it to something different so long as that something requires the same (or greater) memory than the amount of information you plan to extract from the filestream.

1 comment:

  1. And with Search in FileStream:
    function StrContains(const SubStr, Str: string; CaseSensitive: Boolean): Boolean;
    begin
    if CaseSensitive then
    Result := Pos(SubStr, Str) > 0
    else
    Result := Pos(AnsiUpperCase(SubStr), AnsiUpperCase(Str)) > 0;
    end;

    ReplyDelete