Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Pascal Dictionary
  3. TextFile (Text File I/O)

TextFile (Text File I/O)

In Pascal, text file I/O is handled using the TextFile type. Associate a filename with a variable using AssignFile, open the file with Reset (read), Rewrite (write, overwriting), or Append (append), and close it with CloseFile when done. By passing the file variable as the first argument to WriteLn or ReadLn, you can read and write files using the same functions as standard I/O.

Syntax

{ -----------------------------------------------
  Basic text file operations with TextFile
  ----------------------------------------------- }

var
  f : TextFile; { Declare a file variable }

{ Associate the file variable with a file path }
AssignFile(f, 'filename.txt');

{ -----------------------------------------------
  Opening a file (three options)
  ----------------------------------------------- }

{ Open for reading (runtime error if the file does not exist) }
Reset(f);

{ Open for writing from scratch (overwrites existing content) }
Rewrite(f);

{ Open for appending (creates the file if it does not exist) }
Append(f);

{ -----------------------------------------------
  Writing to a file
  ----------------------------------------------- }

{ Write a line followed by a newline (same as standard output) }
WriteLn(f, 'string to write');

{ Write without a trailing newline }
Write(f, 'string to continue on the same line');

{ -----------------------------------------------
  Reading from a file
  ----------------------------------------------- }

{ Read one line into a string variable }
ReadLn(f, variable);

{ Check for end-of-file and read all lines }
while not Eof(f) do begin
  ReadLn(f, variable);
  { Process the line here }
end;

{ -----------------------------------------------
  Close the file (always required)
  ----------------------------------------------- }
CloseFile(f);

Syntax Reference

SyntaxDescription
var f : TextFile;Declares a file variable for text file operations. Text is an alias and can be used instead.
AssignFile(f, 'path')Associates the file variable f with the specified file path. The file is not opened yet at this point.
Reset(f)Opens the file for reading from the beginning. Causes a runtime error if the file does not exist.
Rewrite(f)Opens the file for writing from scratch. If the file already exists, its contents are erased.
Append(f)Opens the file for appending. Writing begins at the end of existing content. Creates the file if it does not exist.
WriteLn(f, value)Writes a value to the file followed by a newline. Identical to the standard WriteLn except for the file variable passed as the first argument.
Write(f, value)Writes a value to the file without a trailing newline. Successive calls append to the same line.
ReadLn(f, variable)Reads one line from the file and consumes the line ending. The value is automatically converted to match the variable's type.
Eof(f)Returns True when the end of the file is reached. The standard pattern for reading all lines is while not Eof(f).
CloseFile(f)Closes the file and releases system resources. Every file that is opened must be closed.

Sample Code

kof_write.pas
{ kof_write.pas — Demonstrates writing to a text file using Rewrite and WriteLn(f) }
{ Writes KOF (The King of Fighters) character data }
{ to a text file }
{
  Compile and run:
    fpc kof_write.pas && ./kof_write
}

program kof_write;

var
  { -----------------------------------------------
    Variable declarations
    ----------------------------------------------- }
  f : TextFile; { File variable }
  fighter_name: string; { Fighter name }
  team_name : string; { Team name }
  power_level : integer; { Power level }

begin
  { -----------------------------------------------
    Associate the file variable with a file path
    ----------------------------------------------- }
  AssignFile(f, 'kof_roster.txt');

  { -----------------------------------------------
    Open the file for writing with Rewrite
    Existing content is erased if the file already exists
    ----------------------------------------------- }
  Rewrite(f);

  { -----------------------------------------------
    Write one line at a time with WriteLn(f, ...)
    The only difference from standard output is the file variable
    passed as the first argument
    ----------------------------------------------- }
  WriteLn(f, '===== KOF Roster =====');
  WriteLn(f, 'Team,Fighter,Power');

  { Write Kusanagi team data }
  WriteLn(f, 'Kusanagi Team,Kusanagi Kyo,9800');
  WriteLn(f, 'Kusanagi Team,Yagami Iori,9750');

  { Write Robert and Ryo data }
  WriteLn(f, 'Art of Fighting Team,Sakazaki Ryo,9200');

  { Write Terry and Andy data }
  WriteLn(f, 'Fatal Fury Team,Bogard Terry,9600');

  { Write King and Mai data }
  WriteLn(f, 'Women Fighters Team,Shiranui Mai,8900');

  WriteLn(f, '===========================');

  { -----------------------------------------------
    Close the file with CloseFile
    Always close any file that was opened
    ----------------------------------------------- }
  CloseFile(f);

  { -----------------------------------------------
    Display a completion message to the terminal
    ----------------------------------------------- }
  WriteLn('Successfully wrote to kof_roster.txt.');
  WriteLn('Output data for 5 fighters.');
end.

Compile and run the program to see the output:

fpc kof_write.pas && ./kof_write
Free Pascal Compiler version ...
Linking ./kof_write
Successfully wrote to kof_roster.txt.
Output data for 5 fighters.
kof_read.pas
{ kof_read.pas — Demonstrates reading a text file using Reset and ReadLn(f) }
{ Reads kof_roster.txt generated by kof_write.pas and }
{ displays all lines while checking for end-of-file with Eof(f) }
{
  Compile and run (run kof_write first):
    fpc kof_read.pas && ./kof_read
}

program kof_read;

var
  { -----------------------------------------------
    Variable declarations
    ----------------------------------------------- }
  f : TextFile; { File variable }
  line : string; { Holds each line read from the file }
  line_num : integer; { Line number counter }

begin
  { -----------------------------------------------
    Associate the file variable with a file path
    ----------------------------------------------- }
  AssignFile(f, 'kof_roster.txt');

  { -----------------------------------------------
    Open the file for reading from the beginning with Reset
    Causes a runtime error if the file does not exist
    ----------------------------------------------- }
  Reset(f);

  { -----------------------------------------------
    Read one line at a time until Eof(f) returns True
    Eof returns True when the end of the file is reached
    ----------------------------------------------- }
  line_num := 0;
  WriteLn('===== Contents of kof_roster.txt =====');

  while not Eof(f) do begin
    { Read one line into the line variable with ReadLn(f, line) }
    ReadLn(f, line);
    line_num := line_num + 1;

    { Print the line with its line number }
    Write(line_num:3, ': ');
    WriteLn(line);
  end;

  WriteLn('=======================================');
  WriteLn('Read ', line_num, ' lines in total.');

  { -----------------------------------------------
    Close the file with CloseFile
    ----------------------------------------------- }
  CloseFile(f);
end.

Compile and run the program to see the output:

fpc kof_read.pas && ./kof_read
Free Pascal Compiler version ...
Linking ./kof_read
===== Contents of kof_roster.txt =====
  1: ===== KOF Roster =====
  2: Team,Fighter,Power
  3: Kusanagi Team,Kusanagi Kyo,9800
  4: Kusanagi Team,Yagami Iori,9750
  5: Art of Fighting Team,Sakazaki Ryo,9200
  6: Fatal Fury Team,Bogard Terry,9600
  7: Women Fighters Team,Shiranui Mai,8900
  8: ===========================
=======================================
Read 8 lines in total.
kof_append.pas
{ kof_append.pas — Demonstrates appending to a text file using Append }
{ Appends new fighter data to the end of kof_roster.txt }
{ Unlike Rewrite, existing content is preserved }
{
  Compile and run (run kof_write first):
    fpc kof_append.pas && ./kof_append
}

program kof_append;

var
  { -----------------------------------------------
    Variable declarations
    ----------------------------------------------- }
  f : TextFile; { File variable }

begin
  { -----------------------------------------------
    Associate the file variable with a file path
    ----------------------------------------------- }
  AssignFile(f, 'kof_roster.txt');

  { -----------------------------------------------
    Open the file for appending with Append
    Existing content is preserved; writing begins at the end
    Creates the file if it does not exist
    ----------------------------------------------- }
  Append(f);

  { -----------------------------------------------
    Write the data to append
    WriteLn(f, ...) adds one line at a time to the end
    ----------------------------------------------- }
  WriteLn(f, ''); { Append a blank line as a separator }
  WriteLn(f, '===== Additional Entries =====');
  WriteLn(f, 'Korea Team,Kim Kaphwan,9100');
  WriteLn(f, 'NESTS,K Prime,9900');
  WriteLn(f, '==============================');

  { -----------------------------------------------
    Close the file with CloseFile
    ----------------------------------------------- }
  CloseFile(f);

  { -----------------------------------------------
    Display a completion message
    ----------------------------------------------- }
  WriteLn('Successfully appended to kof_roster.txt.');
  WriteLn('Added 2 new fighters.');
  WriteLn('Run kof_read again to verify the contents.');
end.

Compile and run the program to see the output:

fpc kof_append.pas && ./kof_append
Free Pascal Compiler version ...
Linking ./kof_append
Successfully appended to kof_roster.txt.
Added 2 new fighters.
Run kof_read again to verify the contents.
kof_score.pas
{ kof_score.pas — Demonstrates reading data from a file and computing statistics }
{ Reads power level data from kof_roster.txt and calculates the maximum and average }
{ Also demonstrates file existence checking with IOResult }
{
  Compile and run (run kof_write first):
    fpc kof_score.pas && ./kof_score
}

program kof_score;

uses
  SysUtils; { Required for StrToIntDef and other conversion functions }

var
  { -----------------------------------------------
    Variable declarations
    ----------------------------------------------- }
  f : TextFile; { File variable }
  line : string; { Each line read from the file }
  field : string; { Each CSV field }
  comma_pos : integer; { Position of the comma character }
  power : integer; { Power level (integer) }
  total_power: integer; { Cumulative power total }
  max_power : integer; { Highest power level found }
  count : integer; { Number of data rows processed }

begin
  { -----------------------------------------------
    {$I-} disables automatic I/O error checking
    Call Reset after AssignFile and check the result with IOResult
    ----------------------------------------------- }
  AssignFile(f, 'kof_roster.txt');

  {$I-}
  Reset(f);
  {$I+}

  { A non-zero IOResult means the file could not be opened }
  if IOResult <> 0 then begin
    WriteLn('Error: kof_roster.txt not found.');
    WriteLn('Run kof_write first to create the file.');
    Halt(1); { Exit the program with exit code 1 }
  end;

  { -----------------------------------------------
    Initialize accumulator variables
    ----------------------------------------------- }
  total_power := 0;
  max_power := 0;
  count := 0;

  { -----------------------------------------------
    Read one line at a time until Eof(f) returns True
    ----------------------------------------------- }
  while not Eof(f) do begin
    ReadLn(f, line);

    { Skip header lines, separator lines, and blank lines }
    if (Length(line) = 0) or (line[1] = '=') or (Pos('Team,Fighter', line) > 0) then
      Continue;

    { Extract the third CSV field (power level) }
    { Find the first comma }
    comma_pos := Pos(',', line);
    if comma_pos = 0 then Continue;
    line := Copy(line, comma_pos + 1, Length(line));

    { Find the second comma }
    comma_pos := Pos(',', line);
    if comma_pos = 0 then Continue;
    field := Copy(line, comma_pos + 1, Length(line));

    { Convert the power level to an integer (returns 0 on failure) }
    power := StrToIntDef(Trim(field), 0);
    if power = 0 then Continue;

    { Update the accumulators }
    total_power := total_power + power;
    count := count + 1;
    if power > max_power then
      max_power := power; { Update the maximum value }
  end;

  CloseFile(f);

  { -----------------------------------------------
    Display the results
    ----------------------------------------------- }
  WriteLn('===== KOF Power Statistics =====');
  if count > 0 then begin
    WriteLn('Fighters counted : ', count);
    WriteLn('Highest power : ', max_power);
    WriteLn('Average power : ', (total_power / count):7:1);
  end else begin
    WriteLn('No data rows found to aggregate.');
  end;
  WriteLn('================================');
end.

Compile and run the program to see the output:

fpc kof_score.pas && ./kof_score
Free Pascal Compiler version ...
Linking ./kof_score
===== KOF Power Statistics =====
Fighters counted :  5
Highest power :  9800
Average power :  9450.0
================================

Notes

Text file operations in Pascal follow the pattern: declare a TextFile variable, call AssignFile, open with Reset, Rewrite, or Append, read or write, then call CloseFile. For writing, use WriteLn(f, value) or Write(f, value); for reading, use ReadLn(f, variable). In each case you switch from standard I/O to file I/O simply by passing the file variable as the first argument. The standard pattern for reading all lines is a while not Eof(f) do loop. Be aware that Rewrite erases any existing content; use Append when you want to preserve existing data and write at the end. To handle a missing file gracefully, temporarily disable automatic I/O error checking with the {$I-} / {$I+} directives and inspect IOResult after the call. For standard I/O fundamentals, see WriteLn / ReadLn (Standard I/O). For string manipulation, see String Functions.

If you find any errors or copyright issues, please .