typed files

From Free Pascal wiki
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Deutsch (de) English (en) polski (pl)

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
  AssignFile(datFile, 'example.txt');

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

  ...
end;

Close the file

begin
  ...
  Close(datFile);  // closes the file
  ...
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