Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 36 ยท Files and Databases

Text Files and TStringList

Read and write text files in Pascal and Delphi with AssignFile, Reset, Rewrite and ReadLn, handle I/O errors, and use TStringList and TFile for modern, shorter code.

Programs that forget everything when they close are toys. Saving a list, reading a configuration file or processing a log all mean working with files. Pascal has had file support since its first version, and Delphi adds a modern layer on top. This lesson covers the classic text-file routines, the TStringList shortcut that most Delphi code uses, and the newer TFile helpers.

This site cannot run Pascal, so the Pascal listings are read-only. The runnable program at the end uses C file functions, which map one to one onto the classic routines, and writes and reads a real file in the sandbox.

The classic way: file variables

A text file is a sequence of lines. In classic Pascal you tie a file variable of type TextFile (older name: Text) to a name on disk, then open it for a purpose:

Step Routine Meaning
connect AssignFile(F, 'notes.txt') link variable and file name; nothing is opened yet
open to read Reset(F) file must exist; start reading at the top
open to write Rewrite(F) create the file, erasing any existing content
open to append Append(F) write at the end of an existing file
use ReadLn, WriteLn, Eof, Eoln one line at a time
close CloseFile(F) flush and release

(Free Pascal also accepts the older Assign and Close names. Delphi renamed them to avoid clashing with other things named Close.)

Writing

PASCAL
var
  F: TextFile;
  I: Integer;
begin
  AssignFile(F, 'squares.txt');
  Rewrite(F);
  try
    for I := 1 to 5 do
      WriteLn(F, I, ' squared is ', I * I);
  finally
    CloseFile(F);
  end;
end.

This produces a five-line file starting with 1 squared is 1 and ending with 5 squared is 25. The first argument of WriteLn is the file variable; leave it out and the text goes to the console.

Reading

PASCAL
var
  F: TextFile;
  Line: string;
  Count: Integer;
begin
  AssignFile(F, 'squares.txt');
  Reset(F);
  try
    Count := 0;
    while not Eof(F) do
    begin
      ReadLn(F, Line);
      Inc(Count);
      WriteLn(Count, ': ', Line);
    end;
  finally
    CloseFile(F);
  end;
end.

Eof(F) becomes true when the last line has been read. The while not Eof loop is the standard shape: it also works for an empty file, where a repeat..until would read garbage.

Handling errors

By default, a failed Reset (missing file) raises EInOutError with a message like "I/O error 2" (file not found). You can handle it with try..except, or you can switch off automatic checking with the {$I-} directive and test IOResult yourself:

PASCAL
AssignFile(F, 'missing.txt');
{$I-}
Reset(F);
{$I+}
if IOResult <> 0 then
  WriteLn('Cannot open the file')
else
begin
  // ... read ...
  CloseFile(F);
end;

IOResult returns 0 for success and a nonzero error code otherwise, and reading it clears it. Forgetting to read it after {$I-} makes the next I/O call fail, a notorious source of confusion. Exceptions are the safer default in new code.

Always check existence with FileExists('name') when a missing file is normal, instead of relying on an error.

The easy way: TStringList

A TStringList (unit System.Classes) holds a list of strings in memory and can load or save a whole file in one call:

PASCAL
uses
  System.Classes;

var
  Lines: TStringList;
  I: Integer;
begin
  Lines := TStringList.Create;
  try
    Lines.LoadFromFile('squares.txt');
    for I := 0 to Lines.Count - 1 do
      WriteLn(I + 1, ': ', Lines[I]);

    Lines.Add('6 squared is 36');
    Lines.Sort;                           // alphabetical
    Lines.SaveToFile('squares-sorted.txt');
  finally
    Lines.Free;
  end;
end.

TStringList is the Swiss Army knife of Delphi code. Useful members:

  • Add, Insert, Delete, IndexOf, Count, and the default array property Lines[I] (zero-based),
  • Text (the whole content as one string) and CommaText (a comma-separated view),
  • Sorted := True and Duplicates := dupIgnore for a sorted set,
  • Values['key'] with Names/ValueFromIndex for key=value pairs, which makes .ini-like data trivial,
  • Delimiter and DelimitedText for splitting strings.

For big files (hundreds of megabytes), loading everything into memory is a bad idea: use the line-by-line style, or a stream (see typed files and streams).

Encoding

Files are bytes, and text needs an encoding. Modern Delphi's TStringList.LoadFromFile detects a byte-order mark and otherwise uses the system's default code page; you can pass TEncoding.UTF8 explicitly. Always write UTF-8 for new files:

PASCAL
Lines.SaveToFile('out.txt', TEncoding.UTF8);

The classic AssignFile routines use the ANSI code page, so non-English text may look wrong. This is one more reason to prefer TStringList, TFile or streams for anything international.

System.IOUtils: TFile and TPath

System.IOUtils gives static helpers that read as one-liners:

PASCAL
uses
  System.IOUtils;

var
  Text: string;
begin
  TFile.WriteAllText('hello.txt', 'Hello, Pascal!', TEncoding.UTF8);
  Text := TFile.ReadAllText('hello.txt', TEncoding.UTF8);
  WriteLn(Text);
  WriteLn(TPath.Combine('data', 'hello.txt'));   // data\hello.txt on Windows
  if TFile.Exists('hello.txt') then
    TFile.Delete('hello.txt');
end.

TPath.Combine builds paths with the right separator for the platform, and TDirectory.GetFiles lists a folder. Free Pascal has TStringList and FileUtil with similar helpers.

The same ideas in C

The runnable program below writes five lines to a file, reads them back one at a time (the while not Eof loop), and then tries to open a missing file and reports the failure, the equivalent of checking IOResult.

C Stand-in: write, read line by line, handle a missing file

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.

Common mistakes

  • Rewrite on a file you meant to append to destroys its content. Use Append.
  • Forgetting CloseFile: the last lines may never reach the disk. Put it in finally.
  • Reading with ReadLn(F, N) into an Integer when a line holds text: it raises an I/O error 106 ("Invalid numeric format").
  • Assuming the current directory: use full paths or TPath.Combine(TPath.GetDocumentsPath, 'x.txt').

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call erases an existing file's content when opening it?

    Rewrite creates the file or truncates it. Reset opens for reading, and Append adds to the end.
  2. 2. What is the standard loop for reading every line of a text file?

    while not Eof checks before each read, so it also works for an empty file.
  3. 3. What does TStringList.LoadFromFile do?

    It loads all lines at once; use streams or line-by-line reading for very large files.
  4. 4. After a call made under {$I-}, what should you do?

    With checking off, errors are reported only through IOResult, and an unread error makes the next I/O call fail.

Summary

  • Classic text I/O: AssignFile, then Reset (read), Rewrite (create/erase) or Append, then ReadLn/WriteLn, then CloseFile.
  • Loop with while not Eof(F); always close in finally.
  • Failed I/O raises EInOutError, or sets IOResult under {$I-}.
  • TStringList loads, edits, sorts and saves whole files; TFile and TPath offer one-liners.
  • Write UTF-8 for new files.

Next: Typed Files and Streams