ZetCode

Modula-2 files

last modified November 27, 2026 Modula-2

In ISO Modula-2 a file is read and written through a channel. A module such as StreamFile opens a channel on a file, and the procedures of TextIO, WholeIO and RealIO read and write on it. They are the procedures of STextIO, SWholeIO and SRealIO with a channel as the first parameter, so everything from the console output and reading input articles carries over.

Writing a file

StreamFile.Open opens a channel on a file. It takes a variable for the channel, the file name, a set of flags, and a variable for the result.

writing.mod
MODULE writing;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, write;
FROM TextIO IMPORT WriteString, WriteLn;
IMPORT STextIO;

VAR
  cid: ChanId;
  res: OpenResults;

BEGIN
  Open(cid, "fruits.txt", write, res);
  IF res = opened THEN
    WriteString(cid, "apple"); WriteLn(cid);
    WriteString(cid, "banana"); WriteLn(cid);
    WriteString(cid, "cherry"); WriteLn(cid);
    Close(cid)
  ELSE
    STextIO.WriteString("cannot create fruits.txt");
    STextIO.WriteLn
  END
END writing.

The flag write asks for output. When the result is opened, cid identifies the channel, and the TextIO procedures write three lines to it. Close writes what is pending and releases the channel. When the file cannot be created, the program reports it on the terminal through STextIO, imported qualified because its names clash with those of TextIO. The program runs twice without complaint: the ISO standard says that write alone needs a new file, but gm2 15.2 replaces an existing one. A program that means to replace a file passes write + old, which works in both.

$ gm2 -fiso writing.mod -o writing
$ ./writing
$ ./writing
$ cat fruits.txt
apple
banana
cherry

Reading a file

The flag read opens an existing file for input. Lines are read with TextIO.ReadString and SkipLine, and IOResult.ReadResult returns the read result of a channel.

reading.mod
MODULE reading;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, read;
FROM TextIO IMPORT ReadString, SkipLine;
FROM IOResult IMPORT ReadResult, ReadResults;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;

VAR
  cid: ChanId;
  res: OpenResults;
  line: ARRAY [0..255] OF CHAR;

BEGIN
  Open(cid, "fruits.txt", read, res);
  IF res # opened THEN
    WriteString("cannot open fruits.txt"); WriteLn
  ELSE
    LOOP
      ReadString(cid, line);
      IF (ReadResult(cid) = endOfInput) AND (Length(line) = 0) THEN
        EXIT
      END;
      WriteString("- "); WriteString(line); WriteLn;
      SkipLine(cid)
    END;
    Close(cid)
  END
END reading.

The loop is the line loop of the reading input article with a channel added to every call. It stops when a read reaches the end of the file and finds no characters, which also handles a last line without a line mark.

$ gm2 -fiso reading.mod -o reading
$ ./reading
- apple
- banana
- cherry

Open results

OpenResults tells why an open failed. Its values include noSuchFile, wrongPermissions, fileExists and otherProblem.

results.mod
MODULE results;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, FlagSet,
  read, write;
FROM STextIO IMPORT WriteString, WriteLn;

PROCEDURE Try(name: ARRAY OF CHAR; flags: FlagSet);
VAR
  cid: ChanId;
  res: OpenResults;
BEGIN
  WriteString(name); WriteString(": ");
  Open(cid, name, flags, res);
  CASE res OF
    opened: WriteString("opened"); Close(cid)
  | noSuchFile: WriteString("no such file")
  | wrongPermissions: WriteString("permission denied")
  | fileExists: WriteString("file exists")
  ELSE
    WriteString("other problem")
  END;
  WriteLn
END Try;

BEGIN
  Try("fruits.txt", read);
  Try("vegetables.txt", read);
  Try("/etc/shadow", read);
  Try("/proc/version", write)
END results.

Try opens a file with the given flags and turns the result into a message. FlagSet is the type of the flags, so a procedure can take them as a parameter. The program is run as an ordinary user, who may read neither /etc/shadow nor write to /proc/version.

$ gm2 -fiso results.mod -o results
$ ./results
fruits.txt: opened
vegetables.txt: no such file
/etc/shadow: permission denied
/proc/version: permission denied

Appending

StreamFile cannot add to the end of a file. SeqFile, the module for sequential files, can: OpenAppend opens a file for writing at its end and creates it if it does not exist.

journal.mod
MODULE journal;
FROM SeqFile IMPORT ChanId, OpenAppend, Close, OpenResults, write;
FROM TextIO IMPORT WriteString, WriteLn;
FROM WholeIO IMPORT WriteCard;
IMPORT STextIO;

VAR
  cid: ChanId;
  res: OpenResults;
  i, sum: CARDINAL;

BEGIN
  sum := 0;
  FOR i := 1 TO 100 DO INC(sum, i) END;
  OpenAppend(cid, "journal.txt", write, res);
  IF res = opened THEN
    WriteString(cid, "sum of 1..100 = ");
    WriteCard(cid, sum, 0);
    WriteLn(cid);
    Close(cid)
  ELSE
    STextIO.WriteString("cannot open journal.txt");
    STextIO.WriteLn
  END
END journal.

The program computes a sum and appends it to journal.txt. SeqFile exports its own ChanId, OpenResults, write and Close, which are the same types and constants as those of StreamFile. WholeIO.WriteCard writes the number to the channel. Each run adds one line.

$ gm2 -fiso journal.mod -o journal
$ ./journal
$ ./journal
$ ./journal
$ cat journal.txt
sum of 1..100 = 5050
sum of 1..100 = 5050
sum of 1..100 = 5050

Writing numbers

WholeIO and RealIO write numbers to a channel with the same field widths as on the terminal.

squares.mod
MODULE squares;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, write, old;
FROM TextIO IMPORT WriteLn;
FROM WholeIO IMPORT WriteCard;
FROM RealIO IMPORT WriteFixed;
IMPORT STextIO;

VAR
  cid: ChanId;
  res: OpenResults;
  n: CARDINAL;

BEGIN
  Open(cid, "squares.txt", write + old, res);
  IF res # opened THEN
    STextIO.WriteString("cannot create squares.txt"); STextIO.WriteLn
  ELSE
    FOR n := 1 TO 6 DO
      WriteCard(cid, n, 2);
      WriteCard(cid, n * n, 4);
      WriteFixed(cid, 1.0 / FLOAT(n), 4, 8);
      WriteLn(cid)
    END;
    Close(cid);
    STextIO.WriteString("wrote squares.txt"); STextIO.WriteLn
  END
END squares.

Each line holds a number, its square and its reciprocal in fixed columns. The flags write + old replace the file if it exists from an earlier run.

$ gm2 -fiso squares.mod -o squares
$ ./squares
wrote squares.txt
$ cat squares.txt
 1   1  1.0000
 2   4  0.5000
 3   9  0.3333
 4  16  0.2500
 5  25  0.2000
 6  36  0.1667

Reading numbers

The next program reads the file back and adds up two of the columns. It reads each line as three tokens and converts them with WholeStr.StrToCard and RealStr.StrToReal.

sums.mod
MODULE sums;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, read;
FROM TextIO IMPORT ReadToken, SkipLine;
FROM IOResult IMPORT ReadResult, ReadResults;
FROM WholeStr IMPORT StrToCard, ConvResults;
FROM RealStr IMPORT StrToReal;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SRealIO IMPORT WriteFixed;

VAR
  cid: ChanId;
  res: OpenResults;
  conv: ConvResults;
  token: ARRAY [0..31] OF CHAR;
  square, total: CARDINAL;
  part, harmonic: REAL;

BEGIN
  Open(cid, "squares.txt", read, res);
  IF res # opened THEN
    WriteString("cannot open squares.txt"); WriteLn
  ELSE
    total := 0;
    harmonic := 0.0;
    LOOP
      ReadToken(cid, token);
      IF ReadResult(cid) = endOfInput THEN EXIT END;
      ReadToken(cid, token);
      StrToCard(token, square, conv);
      ReadToken(cid, token);
      StrToReal(token, part, conv);
      INC(total, square);
      harmonic := harmonic + part;
      SkipLine(cid)
    END;
    Close(cid);
    WriteString("sum of squares:     "); WriteCard(total, 0); WriteLn;
    WriteString("sum of reciprocals: "); WriteFixed(harmonic, 4, 0); WriteLn
  END
END sums.

The first token of a line is the number, which the program does not need; a read of it that reaches the end of the file ends the loop. The conversions are not checked here because the program reads a file written by another program in a known format. Input typed by a person needs the checked conversion of the reading input article. WholeIO.ReadCard and RealIO.ReadReal are avoided for the same reasons as their console versions in gm2 15.2.

$ gm2 -fiso sums.mod -o sums
$ ./sums
sum of squares:     91
sum of reciprocals: 2.4500

Copying a file

Two channels can be open at the same time. The next program copies a file character by character and turns the letters into capitals on the way.

upper.mod
MODULE upper;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, read, write, old;
FROM TextIO IMPORT ReadChar, WriteChar, WriteLn, SkipLine;
FROM IOResult IMPORT ReadResult, ReadResults;
IMPORT STextIO;

PROCEDURE CopyUpper(from, to: ARRAY OF CHAR);
VAR
  src, dst: ChanId;
  res: OpenResults;
  r: ReadResults;
  ch: CHAR;
BEGIN
  Open(src, from, read, res);
  IF res # opened THEN
    STextIO.WriteString("cannot open "); STextIO.WriteString(from);
    STextIO.WriteLn;
    RETURN
  END;
  Open(dst, to, write + old, res);
  IF res # opened THEN
    STextIO.WriteString("cannot create "); STextIO.WriteString(to);
    STextIO.WriteLn;
    Close(src);
    RETURN
  END;
  LOOP
    ReadChar(src, ch);
    r := ReadResult(src);
    IF r = endOfInput THEN EXIT
    ELSIF r = endOfLine THEN WriteLn(dst); SkipLine(src)
    ELSE WriteChar(dst, CAP(ch))
    END
  END;
  Close(src);
  Close(dst)
END CopyUpper;

BEGIN
  CopyUpper("note.txt", "shout.txt")
END upper.

CopyUpper opens the source for reading and the destination for writing; if the second open fails, it closes the first channel before it returns. The loop reads one character at a time with ReadChar and writes it with CAP applied. At the end of a line it writes a line mark to the destination and skips the one in the source, so the copy has the same lines as the original.

$ gm2 -fiso upper.mod -o upper
$ ./upper
$ cat shout.txt
MODULA-2 CAME OUT OF THE LILITH PROJECT.
THE WORKSTATION AND ITS OPERATING SYSTEM
WERE WRITTEN IN THE NEW LANGUAGE.

A CSV report

The last program reads a CSV file of names and points, and writes a report with a grade for each student and the average to another file.

grades.mod
MODULE grades;
FROM StreamFile IMPORT ChanId, Open, Close, OpenResults, read, write, old;
FROM TextIO IMPORT ReadString, SkipLine, WriteString, WriteChar, WriteLn;
FROM WholeIO IMPORT WriteCard;
FROM RealIO IMPORT WriteFixed;
FROM IOResult IMPORT ReadResult, ReadResults;
FROM Strings IMPORT Length, FindNext, Extract;
FROM WholeStr IMPORT StrToCard, ConvResults;
IMPORT STextIO;

VAR
  src, dst: ChanId;
  res: OpenResults;
  conv: ConvResults;
  line, name, field: ARRAY [0..79] OF CHAR;
  found: BOOLEAN;
  comma, points, sum, count, i: CARDINAL;

PROCEDURE Grade(score: CARDINAL): CHAR;
BEGIN
  IF score >= 90 THEN RETURN 'A'
  ELSIF score >= 75 THEN RETURN 'B'
  ELSIF score >= 60 THEN RETURN 'C'
  ELSE RETURN 'F'
  END
END Grade;

BEGIN
  Open(src, "grades.csv", read, res);
  IF res = opened THEN Open(dst, "report.txt", write + old, res) END;
  IF res # opened THEN
    STextIO.WriteString("cannot open the files"); STextIO.WriteLn
  ELSE
    sum := 0; count := 0;
    LOOP
      ReadString(src, line);
      IF (ReadResult(src) = endOfInput) AND (Length(line) = 0) THEN EXIT END;
      SkipLine(src);
      FindNext(",", line, 0, found, comma);
      IF found THEN
        Extract(line, 0, comma, name);
        Extract(line, comma + 1, Length(line) - comma - 1, field);
        StrToCard(field, points, conv);
        WriteString(dst, name);
        FOR i := Length(name) TO 10 DO WriteChar(dst, ' ') END;
        WriteCard(dst, points, 3); WriteString(dst, "  ");
        WriteChar(dst, Grade(points)); WriteLn(dst);
        INC(sum, points); INC(count)
      END
    END;
    WriteString(dst, "average    ");
    WriteFixed(dst, FLOAT(sum) / FLOAT(count), 1, 0); WriteLn(dst);
    Close(src); Close(dst);
    STextIO.WriteString("wrote report.txt"); STextIO.WriteLn
  END
END grades.

Each line is split at the comma. FindNext from the ISO Strings module finds the position of the comma, and two calls of Extract copy the name before it and the points after it. The report pads the names to a fixed width with spaces, writes the points in a field of 3 and the grade from Grade. The first IF opens the report only when the input could be opened, so one test of res covers both files.

$ gm2 -fiso grades.mod -o grades
$ cat grades.csv
Agnes,72
Boris,45
Clara,91
Dusan,60
Eva,88
Filip,79
$ ./grades
wrote report.txt
$ cat report.txt
Agnes       72  C
Boris       45  F
Clara       91  A
Dusan       60  C
Eva         88  B
Filip       79  B
average    72.5

Source

The GNU Modula-2 manual

The ISO libraries in GNU Modula-2

In this article we have opened channels on files with StreamFile and SeqFile, checked the open results, written and read lines, appended to a file, written and read numbers, copied a file character by character and turned a CSV file into a report. The command-line arguments article reads the program arguments through a channel of the same kind, and the reading input article covers the read results in more detail.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.