PDA

View Full Version : Understanding Issue



xGTx
17-07-2004, 08:05 PM
Something I havnt been able to fully understand in the Delphi language is TFileStreams. Can somone please give a semi-detailed overview of what a stream is, how delphi used file streams, the advantages and disadvantages over them etc etc. I would very much appreciate it! thanks

Harry Hunt
17-07-2004, 10:02 PM
There are different types of streams in Delphi. FileStreams is one example but there are also MemoryStreams.
The basically all work the same way: you have a data source of some sort that you can stream data from and to.
Streams have an internal "Pointer" or "Iterator" that marks the current position in the stream. You can set that pointer to a certain position manually using the Seek command. The Pointer will however move by itself as you read data from your stream.

Here's an example


var
FileStream: TFileStream;
Buffer, I: Integer;
begin
FileStream := TFileStream.Create('C:\MyFile.dat', fmOpenRead);
for I := 0 to 100 do
begin
FileStream.Read(Buffer, SizeOf(Buffer));
ListBox1.Items.Add(IntToStr(Buffer));
end;
FileStream.Free;
end;


This example (untested) will open a file and read 100 Integer values from it and display them in a listbox.
In this case, the Buffer is an Integer, but it can be any type of a fixed length. You can read strings from a buffer, but then you will have to specify the length manually.

FileStream.Read(Buffer, SizeOf(Buffer));

This command does the actualy reading. The first parameter tells the FileStream object what to read and where to put it, the second parameter tells the FileStream how much to read. In this case, 32 bits or 4 bytes will be read.

Writing works pretty much the same way as reading, but make sure that when you create the stream, you set the I/O mode to "fmCreate" or "fmOpenWrite"

Harry Hunt
17-07-2004, 10:06 PM
Oh, advantages and disadvantages:
+ Streams are fast
+ TStream decendants are normally compatible with each other. That means you can save a TMemoryStream to a TFileStream and the other way round.
+ TFileStreams can store TComponents (try the Read/WriteComponentRes method)
+ TFileStreams can open files of practically any size
+ Streams unlike FILEs are objects which is pretty good as this allows you to create your own TStream decendants

I don't know of any disadvantages, but that doesn't mean they're not there

xGTx
18-07-2004, 10:03 PM
thanks. Can you save binary data with these? How?

Paulius
18-07-2004, 11:12 PM
Try reading the Help, you want the Write method