Reading Files in Pascal

Our first example demonstrates reading files in Pascal. Reading files is a fundamental task needed for many Pascal programs. Let’s explore various methods of reading files.

program ReadingFiles;

uses
  SysUtils, Classes;

var
  f: TextFile;
  s: string;
  buffer: array[1..5] of Char;
  bytesRead: Integer;

begin
  // Read entire file contents into memory
  s := TFile.ReadAllText('/tmp/dat');
  WriteLn(s);

  // Open file for reading
  AssignFile(f, '/tmp/dat');
  Reset(f);

  // Read some bytes from the beginning of the file
  BlockRead(f, buffer, 5, bytesRead);
  WriteLn(Format('%d bytes: %s', [bytesRead, string(buffer)]));

  // Seek to a specific position and read
  Seek(f, 6);
  BlockRead(f, buffer, 2, bytesRead);
  WriteLn(Format('%d bytes @ %d: %s', [bytesRead, FilePos(f) - bytesRead, string(buffer)]));

  // Seek relative to current position
  Seek(f, FilePos(f) + 4);

  // Seek relative to end of file
  Seek(f, FileSize(f) - 10);

  // Use TStreamReader for buffered reading
  var reader := TStreamReader.Create('/tmp/dat');
  try
    s := reader.ReadLine();
    WriteLn(Format('First line: %s', [s]));
  finally
    reader.Free;
  end;

  // Close the file
  CloseFile(f);
end.

To run this program:

$ echo "hello" > /tmp/dat
$ echo "pascal" >> /tmp/dat
$ fpc reading_files.pas
$ ./reading_files
hello
pascal
5 bytes: hello
2 bytes @ 6: pa
First line: hello

This example demonstrates various file reading techniques in Pascal:

  1. Reading an entire file into memory using TFile.ReadAllText.
  2. Opening a file and reading specific bytes using BlockRead.
  3. Seeking to different positions in the file using Seek.
  4. Using TStreamReader for buffered reading.

Note that Pascal uses AssignFile and Reset to open files, and CloseFile to close them. The Seek function is used for positioning within the file, and FilePos returns the current position.

Unlike Go, Pascal doesn’t have a built-in error handling mechanism like defer. Instead, you should use try-finally blocks to ensure resources are properly released.

In the next example, we’ll explore writing files in Pascal.