Simple read/write record .dat file in Delphi

后端 未结 3 747
悲哀的现实
悲哀的现实 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:04

    Use streams. Here is a simple demo (just demo - in practice there is no need to reopen file stream every time):

    type
      Scores = record
        name: string[50];
        score: integer;
      end;
    
    var rank: array[1..3] of scores;
    
    procedure WriteScores(var Buf; Count: Integer);
    var
      Stream: TStream;
    
    begin
      Stream:= TFileStream.Create('test.dat', fmCreate);
      try
        Stream.WriteBuffer(Buf, SizeOf(Scores) * Count);
      finally
        Stream.Free;
      end;
    end;
    
    procedure ReadScore(var Buf; Index: Integer);
    var
      Stream: TStream;
    
    begin
      Stream:= TFileStream.Create('test.dat', fmOpenRead or fmShareDenyWrite);
      try
        Stream.Position:= Index * SizeOf(Scores);
        Stream.ReadBuffer(Buf, SizeOf(Scores));
      finally
        Stream.Free;
      end;
    end;
    
    // write rank[1..3] to test.dat
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      rank[2].name:= '123';
      WriteScores(rank, Length(Rank));
    end;
    
    // read rank[2] from test.dat
    procedure TForm1.Button2Click(Sender: TObject);
    begin
      rank[2].name:= '';
      ReadScore(rank[2], 2 - Low(rank));
      ShowMessage(rank[2].name);
    end;
    
    0 讨论(0)
  • 2021-01-05 07:15

    Look in the help under "blockread" and or "blockwrite". There probably will be an example

    0 讨论(0)
  • 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; 
    
    0 讨论(0)
提交回复
热议问题