Danny Robinson
Danny Robinson

Reputation: 35

Loading information from a text file in Delphi 7

I am attempting to save names and scores to a text file with one program and load it from the file in another. The issue is in referencing each name rather than just loading the whole file or just the first name.

It is saved as such:

scores = record
        name: string[20];
        Score: integer;

procedure TForm1.BtnSaveClick(Sender: TObject);
var
scoresFile: file of scores;
begin
scoresrecord.name := EdtName.Text;
scoresrecord.Score := Score;
assignfile(scoresFile, 'Teacher.txt');
rewrite(scoresFile);
write(scoresFile, scoresrecord);
closeFile(scoresFile);
end; 

and loaded into a string grid using:

 scores = record
        name: string[20];
        Score: integer;

var 
ScoreRecord: scores;
scoresFile: file of scores;

StrGrdScores.Cells[0,0]:='Name';
StrGrdScores.Cells[1,0]:='Score';
assignfile(scoresFile, 'C:\Computing\AlgebraNew\Teacher.txt');
reset(scoresFile);
while not Eof(scoresFile) do
read(scoresFile, ScoreRecord);
closeFile(scoresFile);
for I := 1 to StrGrdScores.Row do
StrGrdScores.cells[0,i]:=ScoreRecord.name;

This is my attempt to load the names, but it just loads the first name in the file into each row. When I work out how to load the names, loading the scores should be obvious. Any help is much appreciated.

Upvotes: 2

Views: 1911

Answers (2)

Stijn Sanders
Stijn Sanders

Reputation: 36850

assignfile/write/rewrite/closefile is very old-style Pascal. In Object Pascal and specifically Delphi, there's the TFileStream object to use. But in this specific case, I would suggest the TStringList object. It has LoadFromFile and SaveToFile methods, but also an indexed property Value, which stores values in lines with "Name=Value".

Upvotes: 4

Jeff Cuscutis
Jeff Cuscutis

Reputation: 11647

Your save procedure appears to only save one record to the file.

Your load procedure reads each row into the same variable, overwriting the previous values. Write the values into the grid as you read them from the file.

i = 0;
while not Eof(scoresFile) do
begin
  read(scoresFile, ScoreRecord);
  StrGrdScores.cells[0,i]:=ScoreRecord.name;
  StrGrdScores.cells[1,i]:=ScoreRecord.Score;
  inc(i);
end;
closeFile(scoresFile);

You may need to append a row to the stringgrid before writing the value.

Upvotes: 5

Related Questions