Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple read/write record .dat file in Delphi

For some reason my OpenID account no longer exists even when I used it yesterday. But anyway.

I need to save record data into a .dat file. I tried a lot of searching, but it was all related to databases and BLOB things. I wasn't able to construct anything from it.

I have the following record

   type
   Scores = record
     name: string[50];
     score: integer;
   end;  

var rank: array[1..3] of scores;

I just need a simple way of saving and reading the record data from a .dat file. I had the book on how to do it, but that's at school.

like image 928
Skeela87 Avatar asked Apr 23 '11 08:04

Skeela87


1 Answers

You should also take a look at the file of-method.

This is kinda out-dated, but it's a nice way to learn how to work with files.

Since records with dynamic arrays (including ordinary strings) can't be stored to files with this method, unicode strings will not be supported. But string[50] is based on ShortStrings and your record is therefore already non-unicode...

Write to file

var
  i: Integer;
  myFile: File of TScores;
begin
  AssignFile(myFile,'Rank.dat');
  Rewrite(myFile);

  try
    for i := 1 to 3 do
      Write(myFile, Rank[i]);
 finally
   CloseFile(myFile);
 end;
end; 

Read from file

var
  i: Integer;
  Scores: TScores;
  myFile: File of TScores;
begin
  AssignFile(myFile, 'Rank.dat');
  Reset(myFile);

  try
    i := 1;
    while not EOF(myFile) do 
    begin
      Read(myFile, Scores);
      Rank[i] := Scores;      //You will get an error if i is out of the array bounds. I.e. more than 3
      Inc(i);
    end;
  finally
   CloseFile(myFile);
  end;
 end; 
like image 77
Jørn E. Angeltveit Avatar answered Sep 29 '22 11:09

Jørn E. Angeltveit