Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 36 ยท Files and Databases

Typed Files and Streams

Store records in Pascal typed files with Seek and FileSize, copy raw bytes with BlockRead and BlockWrite, and use TFileStream and TMemoryStream, with a runnable C record-file model.

Text files are easy to read but awkward for data: to change the fifth record you must rewrite the whole file, and numbers are stored as text you must parse again. Pascal has a feature that C-family languages lack in the core language: the typed file, a file of records of one type, where you can jump to any record by number.

This lesson covers typed files, untyped files (raw bytes), and the stream classes that replace both in modern Delphi code.

Pascal listings are read-only here. The runnable program at the end uses fread, fwrite and fseek on a record file in C, which is the same model.

Typed files: a file of records

Declare a file type with file of plus a record (or any fixed-size type):

PASCAL
type
  TStudent = record
    Id: Integer;
    Name: string[20];      // a short string: fixed size
    Grade: Double;
  end;

var
  F: file of TStudent;
  S: TStudent;
begin
  AssignFile(F, 'students.dat');
  Rewrite(F);
  try
    S.Id := 1; S.Name := 'Ada';   S.Grade := 9.5;  Write(F, S);
    S.Id := 2; S.Name := 'Linus'; S.Grade := 8.0;  Write(F, S);
    S.Id := 3; S.Name := 'Grace'; S.Grade := 9.9;  Write(F, S);
  finally
    CloseFile(F);
  end;
end.

The record must have a fixed size. A normal string is a pointer to separately allocated text, so it cannot be stored in a record written to a file. That is why the example uses string[20] (a ShortString holding up to 20 bytes), or a array[0..19] of Char. Every record then takes the same number of bytes, and a record number maps directly to a position in the file.

Random access

Routine Purpose
Write(F, Rec) / Read(F, Rec) write or read one record at the current position, then advance
Seek(F, N) move to record number N (counting from 0)
FilePos(F) current record number
FileSize(F) number of records
Truncate(F) cut the file at the current position
Reset(F) open an existing file; typed files can be read and written
PASCAL
Reset(F);
try
  WriteLn('Records: ', FileSize(F));    // 3
  Seek(F, 1);                            // the second record
  Read(F, S);
  S.Grade := 8.5;
  Seek(F, 1);                            // Read advanced the position: go back
  Write(F, S);                           // overwrite that one record only
finally
  CloseFile(F);
end;

Notice that Read moves the position forward, so you must Seek back before writing over the same record. Forgetting that, so the update lands on the next record, is the classic typed-file bug.

To append, Seek(F, FileSize(F)) and then Write. To delete a record you copy the later records one slot down and Truncate, or mark the record with a Deleted: Boolean field.

Records sit at fixed offsets

Record 0 Starts at byte 0
Record 1 Starts at SizeOf(T)
Record N Starts at N x SizeOf(T)
Seek(F, N) Jumps straight there

No need to read earlier records

1 / 2

Untyped files and BlockRead

A file with no type is a bag of bytes. You choose how many bytes make a "record" when you open it, and move data in blocks with BlockRead and BlockWrite, the fastest classic way to copy a file:

PASCAL
var
  Src, Dst: file;
  Buf: array[0..4095] of Byte;
  Got, Put: Integer;
begin
  AssignFile(Src, 'big.bin');  Reset(Src, 1);     // record size = 1 byte
  AssignFile(Dst, 'copy.bin'); Rewrite(Dst, 1);
  try
    repeat
      BlockRead(Src, Buf, SizeOf(Buf), Got);
      if Got > 0 then
        BlockWrite(Dst, Buf, Got, Put);
    until Got = 0;
  finally
    CloseFile(Src);
    CloseFile(Dst);
  end;
end.

Reset(Src, 1) sets the record size to one byte, so the counts are in bytes. Got reports how many were actually read, which is less than the buffer at the end of the file.

Streams

Delphi's TStream classes (unit System.Classes) are the modern way to read and write bytes. They share one interface, so code written against TStream works with a file, memory, a network socket or a compressed stream.

Class Backing store
TFileStream a file on disk
TMemoryStream a growable block of memory
TStringStream a string
TBytesStream a TBytes array
PASCAL
var
  FS: TFileStream;
  Magic: array[0..3] of AnsiChar;
  Count: Integer;
begin
  FS := TFileStream.Create('data.bin', fmOpenRead or fmShareDenyWrite);
  try
    FS.ReadBuffer(Magic, SizeOf(Magic));   // raises if not enough bytes
    FS.ReadBuffer(Count, SizeOf(Count));
    WriteLn('Magic: ', Magic, ', count: ', Count);
    WriteLn('Size: ', FS.Size, ' Position: ', FS.Position);
  finally
    FS.Free;
  end;
end.

Read/Write return the number of bytes moved and never raise on a short transfer; ReadBuffer/WriteBuffer raise an exception if they cannot move all the bytes asked for, which is usually what you want. Position and Size work like Seek and FileSize, but in bytes. CopyFrom(Source, Count) copies between streams; Count = 0 copies everything.

Streams are also how components save themselves (forms are streamed to .dfm files) and how TStringList talks to files under the hood. For large data, streams avoid loading everything into memory: you read in chunks.

Record files in C

The program below stores three student records in a binary file, reopens it, jumps straight to record 1 with fseek, updates it, and reads back all records. Each C struct has a fixed size, the same condition Pascal requires. (The binary layout includes padding, so such files are not portable between compilers; in Pascal, packed record guarantees a layout without padding.)

C Stand-in: a file of records with random access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Remove the second fseek and run again: the update lands on record 2, overwriting Grace, because the read had already moved the position. It is the same bug as in Pascal.

When to use what

  • Text file or TStringList: human-readable data, configuration, logs.
  • Typed file: small fixed-record data you must update in place. It is fine for learning projects and tiny tools.
  • Streams: anything byte-oriented, large, or passed between components.
  • A database (next lesson): once you need searching, several users, or relationships.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a normal string field not be stored in a record written to a typed file?

    Only the pointer would be written. Use string[20] or a fixed char array so every record has the same size and holds its own data.
  2. 2. After Read(F, S) on record 5, you want to rewrite that same record. What must you do before Write?

    Each Read or Write moves the file position to the next record.
  3. 3. What does FileSize(F) return for a typed file?

    For typed files FileSize counts records, not bytes.
  4. 4. Which stream method raises an exception if fewer bytes than requested are available?

    Read returns a count; ReadBuffer raises EReadError on a short read.

Summary

  • A typed file (file of T) stores fixed-size records and allows random access with Seek, FilePos and FileSize.
  • Use fixed-size fields (string[20], arrays) in records saved to files.
  • Read and Write advance the position: seek back to update in place.
  • Untyped files copy bytes with BlockRead/BlockWrite.
  • TStream descendants (TFileStream, TMemoryStream) are the modern, flexible way to handle bytes.

Next: Databases with FireDAC