PDA

View Full Version : Saving many records to file



BytePtr
01-11-2005, 12:56 PM
Im not newbie in programming, just trying to learn more every day with my experiments.
I need to create one specific file, like described in documenttation of file format. But my problem is how to write many records in file? Look my code.


type
tmy_file_header=record
file_type:array[0..3] of Char;
vers_code:Word;
end;

mfh: tmy_file_header;
f: file of tmy_file_header;

procedure TForm1.Button1Click(Sender: TObject);
begin
assignfile(f,'c:\data.dat');
{$I-}
reset(f);
seek(f, filesize(f));
{$I+}
if ioresult=0 then
begin
// write
mfh.file_type:='MHDR';
mfh.vers_code:=100;
write(f,mfh);
end
else
begin
{$I-}
rewrite(f);
{$I+}
if ioresult=0 then
begin
// write
mfh.file_type:='MHDR';
mfh.vers_code:=100;
write(f,mfh);
end
else
showmessage('Unable to create file!');
end;
end;

tmy_file_header is my first record, but i must to create more records and write them all to one file, without removing/corrupting previous data from/in file.

If i write another:
f: file of other_record; then Delphi displays error: "Incompatible types: first record and other record"

Creating every time new F type is not good way.
How to solve this problem? Any ideas?

btw: i just started learning using delphi "record and type".

cairnswm
01-11-2005, 01:29 PM
Have a look at BlockRead and Blockwrite. They allow you to write records of anysize to a file.

BytePtr
01-11-2005, 02:19 PM
Thanks for reply.
I decided to use streams. I think they solved my problem.


type
tmy_header=record
f_type:array[0..3] of char;
codez:word;
end;

tmy_header2=record
typez:array[0..3] of char;
sizez:longword;
end;

mh: tmy_header
cht: tmy_header2;

fname: string; // filename
fstream: tfilestream;

procedure TForm1.Button1Click(Sender: TObject);
begin
fname:='c:\data.dat';
fstream:=tfilestream.Create(fname, fmCreate or fmOpenWrite or fmShareExclusive);
try
mh.f_type:='MHDR';
mh.codez:=100;

cht.typez:='RDHM';
cht.sizez:=255;

fstream.Write(mh,sizeof(mh));
fstream.Write(cht,sizeof(cht));

finally
fstream.Free;
end;

Now the data is correctly in my file, i will try to write more and look how it will work.I have original editor for this file, so i can test with this also, how it loads my file after i create it with my program. Until now it loads my created file OK.
If i have any problems with this, then i will let u know.

Thanks so far :)