[fpc-pascal]TFileStream
Full_Name
memsom at post.interalpha.co.uk
Fri Sep 7 11:07:02 CEST 2001
Quoting Michael Van Canneyt <michael.vancanneyt at wisa.be>:
If TFileStream is the same as Delphi's class, the following should work:
WRITE:
var
fs: TFileStream;
teststr: string;
i: integer;
begin
teststr := 'THIS IS A TEST STRING';
fs := TFileStream.Create('c:\out\text.txt', fmCreate);
try
for i := 1 to length(teststr) do
fs.Write(teststr[i], sizeof(char));
finally
fs.free;
end;
end;
READ:
var
fs: TFileStream;
teststr: string;
a: char;
i: integer;
begin
teststr := '';
fs := TFileStream.Create('c:\out\text.txt', fmOpenRead);
try
fs.Position := 0;
for i := 1 to fs.size do begin
fs.Read(a, sizeof(char));
teststr := teststr + a;
end;
finally
fs.free;
end;
writeln(teststr);
end;
These examples are a bit cheesey (not how I would personally do things), but
they are taken from an example I knocked up for a delegate on a course I taught
a while back. He wanted a simple example of how to read and write to files.
Using this basic template, you could change 'char' for any type (word, integer,
record etc).. Strings are tricky, as Delphi does some clever stuff behind the
scenes, but FPC might allow them to be used directly.
open(stream)
while not(eof(stream))
packet=read(stream,size) <-- read a record of fixed length
parse(packet)
end
close(stream)
could be translated as (untested):
var
fs: TFileStream;
aPacket: TPacket; //defined as whatever you like else where
i: integer;
begin
teststr := '';
fs := TFileStream.Create('c:\filetoread.ext', fmOpenRead); //opens stream
try
fs.Position := 0; //make double sure at start.. delphi doesn't
//open at position '0'... not always, anyway...
{may want a check to make sure there's enough file left to read..
otherwise this may fail/never exit... }
while (fs.position < fs.size) {NB ^ see above..} do begin
fs.Read(aPacket, sizeof(TPacket));
parse(aPacket); //defined somewhere else...
//however, this should handle the 'endless loop' scenario..
if (fs.size - fs.position < sizeof(TPacket) then break;
fs.position := fs.position + sizeof(TPacket); //inc the position
end;
finally
fs.free; //closes stream
end;
end;
Something like that.. I once wrote a unit that reads/writes ZX Spectrum SNA
files and lets you see the dump of the memory using a similar technique.
The above is untested, it might not work.. should give you the jist though.
--
"Computer games don't affect kids; I mean if Pac-Man affected us as kids,
we'd all be running around in darkened rooms, munching magic pills and
listening to repetitive electronic music."
Kristian Wilson,
Nintendo, Inc, 1989
-----BEGIN GEEK CODE BLOCK-----
Version: 3.12
GCS d? s+++:+ a- C++ UL+ P L++ E---- W- N+ o+ K- w
O- M V PS PE-- Y PGP- t- 5-- X- R- tv+ b+ DI++ D+
G e++ h--- r+++ y+++
------END GEEK CODE BLOCK------
More information about the fpc-pascal
mailing list