Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Saving array of records to file?

Status
Not open for further replies.

spoondyke

Programmer
Nov 26, 2001
19
GB
I am having problems saving/opening an array of records to/from a file. For some reason all the data is turning to garbage on the save.
Can anyone help me in this area or point me to a good tutorial on this subject?

thanks
 
Code:
F: File of RecordType;

AssignFile(F, 'data.dat');
Rewrite(F);
for i := Low(recordArray) to High(recordArray) do
   Write(F, recordArray[i]);
CloseFile(F);

If you still have problems paste the offending code.
 
Check in the pascal forum the FAQ about files S. van Els
SAvanEls@cq-link.sr
 
How have you declared your array? If your using pointers and write a pointer without dereferencing it you will get the problem that you outlining.

Roger
 
I have given the sample code to save the record from array into file. Dynamically create the array then it will set the higher bound in dynamic. Otherwise it will have fixed the higher bound what we difined. For eg. array [1..100] of recordtype will fixed the higher bound to 100. Suppose we will have 10 records to save. But it will write 100 Records. So you are getting garbage. Following code can you some more inputs for your case.


uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

type
RecordType = Record
name : string[25];
code : integer;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
arr : array of RecordType;
Procedure sample;

{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
var
f1 : file of recordtype;
i :integer;
begin
assignfile(f1,'d:\data.dat');
rewrite(f1);
sample;
for i := Low(arr) to High(arr) do
begin
write(f1, arr);
end;
CloseFile(F1);
end;
procedure TForm1.sample;
var
i : integer;
begin
for i := 1 to 10 do
begin
setlength(arr,i); {Defining the dynamic array}
arr.name := 'Data '+ Inttostr(i);
arr.code := i;
end;
end;

end.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top