Typed files

This is an old revision of Typed files, edited by Thaddy at . The current revision is 135904.

/* Close the file */

Typed file

A typed text file is suitable for processing files of any size. A typed text file consists of individual data records. All records in the file have the same structure. This means that each data record is of the same length.

Set the file and record structure

The structure applies to the file type and the record type. The file and data record must have the same structure.

 type
   TMemployee = Record
   strName : String[20];
   sinContent : Single;
 end;

Create the file

var
  datFile : File of TMemployee;
  recData : TMemployee;
begin
  system.Assign(datFile, 'example.txt');

  // An existing file is deleted and re-created
  ReWrite(datFile);

  ...
end;

Or:

var
  datFile : File of TMemployee;
  recData : TMemployee;
begin
  AssignFile(datFile, 'example.txt'); // calls the above, only mode ObjFpc and mode Delphi

  // An existing file is deleted and re-created
  ReWrite(datFile);

  ...
end;

Close the file

begin
  ...
  System.Close(datFile);  // closes the file
  ...
end;

Or

begin
  ...
  CloseFile(datFile);  // calls the above, only mode ObjFpc and mode Delphi
  ...
end;

Write data record

var
  datFile : File of TMemployee;
  recData : TMemployee;
begin
  ...

  // fill the record
  recData.strName := 'abcdefghij';
  recData.sinContent := 1700.21;

  // write the record to the file
  Write(datFile, recData); 

  ...
end;

Read data record

var
  datFile : File of TMemployee;
  recData : TMemployee;
begin
  AssignFile(datFile, 'example.txt');

  Reset(datFile);          // Set the file pointer to the beginning of the file

  Read(datFile, recData);  // Reads a record from the file
  ...
end;

Read file completely

var
  datFile : File of TMemployee;
  recData : TMemployee;
begin
  AssignFile(datFile, 'example.txt');
  Reset (datFile);

  while not eof(datFile)      // as long as data can still be read
    do begin
      read(datFile, recData); // read record from file
      ...
    end;

  CloseFile (datFile);
end;

Position pointer on a data record

begin
  AssignFile(datFile, 'example.txt');
  Reset(datFile);
  ...

  Seek(datFile, 0);        // position file pointer at start of first record
  Read(datFile, recData);  // read first record into recData variable

  recData.sinContent := 1602.22; // update record 

  Seek(datFile, 0);              // position file pointer at start of first record
  Write(datFile, recData);       // write first record back

  ...
end;

See also