Simple read/write record .dat file in Delphi

后端 未结 3 750
悲哀的现实
悲哀的现实 2021-01-05 06:58

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

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 07:21

    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; 
    

提交回复
热议问题