Answer the question
In order to leave comments, you need to log in
How in Delphi to save data to a typed file, and also read information from it?
It is required to save data to a typed file, as well as read information from it.
Here is the record structure:
type
phonebook=record
firstname:string[255];
lastname:string[255];
phonenumber:string[255];
adress:string[255];
end;
var
Form1: TForm1;
pb:phonebook;
F:File of phonebook;
i,j,n,k:integer;
AssignFile(F, 'pbook.dat');
Rewrite(f);
n:=0;
for i:=1 to StringGrid1.RowCount do
begin
pb.firstname:=StringGrid1.Cells[1,i];
pb.lastname:=StringGrid1.Cells[2,i];
pb.phonenumber:=StringGrid1.Cells[3,i];
pb.adress:=StringGrid1.Cells[4,i];
Write(F,pb);
n:=n+1;
Seek(F,n);
end;
CloseFile(F);
AssignFile(F, 'pbook.dat');
Reset(F);
n:=0;
while not eof(F) do
begin
for i:=1 to StringGrid1.RowCount do
begin
with pb do
begin
Seek(F,n);
Read(F,pb);
StringGrid1.Cells[1,i]:=firstname;
StringGrid1.Cells[2,i]:=lastname;
StringGrid1.Cells[3,i]:=phonenumber;
StringGrid1.Cells[4,i]:=adress;
StringGrid1.RowCount:=StringGrid1.RowCount+1;
inc(n);
end;
end;
end;
Answer the question
In order to leave comments, you need to log in
Why do Seek all the time? By the way records with 0 are numbered.
If memory does not change when working with records, Rewrite takes two values.
If there are headings then
In reading it is generally not clear what is written.
There are two cycles. And in one of them, an attempt to modify the counter limit (by the way, most likely will not work either). That is, if we have 10 records in the file, we count one as the first pass, two as the second, and so on, until the 11th pass, when we try to count 11 records, that is, more than there are in the file.
I would recommend looking at other people's examples.
Save to file:
AssignFile(F, 'pbook.dat');
Rewrite(f);
for i:=1 to StringGrid1.RowCount-1 do
begin
pb.firstname:=StringGrid1.Cells[1,i];
pb.lastname:=StringGrid1.Cells[2,i];
pb.phonenumber:=StringGrid1.Cells[3,i];
pb.adress:=StringGrid1.Cells[4,i];
Write(F,pb);
end;
CloseFile(F);
AssignFile(F, 'pbook.dat');
Reset(F);
StringGrid1.RowCount := FileSize(F) + 1; // Точно не помню
Seek(F, 0); // Может быть не нужен
i := 1;
while not eof(F) do
begin
with pb do
begin
Read(F,pb);
StringGrid1.Cells[1,i]:=firstname;
StringGrid1.Cells[2,i]:=lastname;
StringGrid1.Cells[3,i]:=phonenumber;
StringGrid1.Cells[4,i]:=adress;
Inc(i);
end;
end;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question