Domanda

Having difficulty reading data from binary file into a simple array of records, where the array is fixed (via a constant = 3). I have searched forum for a solution but no joy.

Here is my array structure:

Const NoOfRecentScores = 3;
Type
  TRecentScore = Record
                   Name : String[25];
                   Score : Integer;
                 End;

  TRecentScores = Array[1..NoOfRecentScores] of TRecentScore;

Var
  RecentScores : TRecentScores;

Here is my procedure that attempts to load the 3 scores from a binary file...

Procedure LoadRecentScores (var RecentScores:TRecentScores);
var MasterFile: File of TRecentScore;
    MasterFileName: String;
    count:integer;
Begin
  MasterFileName:='HighScores.bin';
  if fileexists(MasterFileName) then
    begin
      Assignfile(MasterFile, MasterFilename);
      Reset(MasterFile);

      While not EOF(MasterFile) do
        begin
          Read(Masterfile, RecentScores[count]); // issue with this line?
          count:= count +1 ;
        end;
      Writeln(Count, ' records retrieved from file. Press ENTER to continue');
      close(Masterfile);
    end
  else
    begin
      Writeln('File not found. Press ENTER to continue');
      readln;
    end;
end;  

The issue seems to be with the commented line...what is the issue here? When i compile and run the program, it exits unexpectedly.

È stato utile?

Soluzione

You need to initialize count before using it the first time. (You should probably include an escape as well, to keep from running off the end of the array if you get more data than your code expects.)

count := 1;
while (not EOF(MasterFile)) and (Count <= NoOfRecentScores) do
begin
  Read(MasterFile, RecentScores[count];
  Inc(Count);  // or Count := Count + 1;

end;

Local variables are not initialized in Pascal, meaning that until you assign a value they can contain any random memory content.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top