1

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You should note that if you enable hints and warnings, the compiler will tell you about this sort of problem. In this case, you would have gotten a message saying something like "Warning: Variable may not have been initialized". How to enable them depends on the compiler and IDE you're using; I don't have a copy of Lazarus or FPC on this machine, so I don't know where to enable these messages there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.