TFileStream and TMemoryStream Classes in Delphi
TFileStream and TMemoryStream Classes in Delphi
TFileStream class is descendant of THandleStream and is used for manipulating file data. TMemoryStream is used for manipulating data in memory. TMemoryStream is descendant of TStream class. This class introduces read-only property called Memory which is of pointer type. So, you can get direct access to memory maintained by TMemoryStream.
TFileStream class usage in Delphi
Following is the simple delphi program to load a file name 'c:\mydata.dat' for read access into stream and then read 4 bytes from beginning of file into a variable.
var
afile_st : TFileStream;
temp_data: cardinal;
...
afile_st:=TFileStream.Create('c:\mydata.dat', fmOpenRead);
try
//make sure file pointer is on beginning of file
afile_st.Seek(0, soFromBeginning);
//read buffer
afile_st.ReadBuffer(temp_data, 4);
finally
afile_st.Free;
end;
TMemoryStream class usage in Delphi
Use TMemoryStream to store data in a dynamic memory buffer that is enhanced with file-like access capabilities. TMemoryStream provides the general I/O capabilities of a stream object while introducing methods and properties to manage a dynamic memory buffer.
Following is the simple delphi program to load data from a file to memory.
Following is the simple delphi program to load data from a file to memory.
var
memStream:TMemoryStream;
...
memStream:=TMemoryStream.Create;
try
LoadFromFileToMem('C\myFile.dat',memStream);
finally
memStream.Free;
end;
procedure LoadFromFileToMem(const filename:string; memStream:TMemoryStream);
var
afileStream:TFileStream;
begin
afileStream:=TFileStream.Create(filename, fmOpenRead);
try
memStream.CopyFrom(afileStream);
finally
afileStream.Free;
end;
end;