Writing and reading text files

A file in Fortran is a number: a unit. A program connects a name to a unit with open, writes or reads through the unit, and closes it at the end. Everything the earlier lessons did with print and read from the keyboard works on a unit unchanged, which is why a text file is the easiest thing to add to a program that already prints.

OPEN, WRITE and CLOSE

open (newunit=u, file="scores.txt", status="replace", action="write") does three things: it picks a free unit number and stores it in u, it connects the name, and it says that the file may be created or overwritten and that the program only intends to write. The status keyword has four common values: replace creates or truncates, old requires an existing file, new requires that the file does not exist, and unknown leaves the decision to the program.

The file file_demo.f90 writes four records and then reads them back:

program file_demo implicit none integer :: i, u, ios, n character(len=80) :: line open (newunit=u, file="scores.txt", status="replace", action="write") write (u, '(a)') "# scores" do i = 1, 3 write (u, '(i3,f8.2)') i, 10.0 * i end do close (u) open (newunit=u, file="scores.txt", status="old", action="read") n = 0 do read (u, '(a)', iostat=ios) line if (ios /= 0) exit n = n + 1 print '(i2,a,a)', n, ": ", trim(line) end do close (u) print *, "records :", n end program file_demo

gfortran -Wall -Wextra -std=f2018 file_demo.f90 -o file_demo
./file_demo

1: # scores
2: 1 10.00
3: 2 20.00
4: 3 30.00
records : 4

The program reads the file it has just written, which proves the round trip: each write produced one record and each read took one. The file holds forty-five bytes on this machine, four records and the line endings, and the program never saw a name after the two open calls.

Reading the file back

The read loop is the one from the standard input lesson with a unit in place of the star: read a record, stop when the status is not zero, and count what came. The status here carries an extra meaning, because a damaged or unreadable file also reports a nonzero status, and a program that must tell the end of the data from a read error tests the sign of ios.

action="read" and action="write" are promises to the compiler and to the operating system: a program that writes to a unit opened for reading is an error. The default, action="readwrite", allows both, and it is the one to avoid when one of the two is a mistake.

Appending to a file

position="append" opens a file with the record pointer after the last record, so a write adds a line instead of replacing the first one. The program below writes one line, closes the file, and opens it again to add a second.

program append_demo implicit none integer :: u, ios character(len=80) :: line open (newunit=u, file="log.txt", status="replace", action="write") write (u, '(a)') "first run" close (u) open (newunit=u, file="log.txt", status="old", position="append", action="write") write (u, '(a)') "second run" close (u) open (newunit=u, file="log.txt", status="old", action="read") do read (u, '(a)', iostat=ios) line if (ios /= 0) exit print '(a,a)', "line: ", trim(line) end do close (u) end program append_demo

gfortran -Wall -Wextra -std=f2018 append.f90 -o append
./append

line: first run
line: second run

Without position="append" the second open would have started at the beginning of the file, and the write would have replaced the first record in place because both lines are the same length. That silent overwrite is one of the reasons a log file is opened with append and nothing else.

INQUIRE

inquire (file=..., exist=...) asks the operating system a question about a name without opening it, and the other keywords of the statement answer what a program needs before an open: the size, the name, whether the file is open and by which unit, and whether it is readable or writable.

program inquire_demo implicit none integer :: u, sz logical :: there open (newunit=u, file="data.txt", status="replace", action="write") write (u, '(a)') "hello" write (u, '(a)') "world" close (u) inquire (file="data.txt", exist=there, size=sz) print *, "exists :", there print *, "size :", sz inquire (file="nosuch.txt", exist=there) print *, "missing:", there end program inquire_demo

gfortran -Wall -Wextra -std=f2018 inquire.f90 -o inquire
./inquire

exists : T
size : 12
missing: F

Twelve bytes are two records of five letters and one line ending each. The size is the size on disk, so it counts the line endings and any byte a text editor added; a program that wants the number of records reads them and counts, as the first program did.

Units and NEWUNIT

Before Fortran 2008 a program picked a unit number itself, usually ten or twenty, and two parts of a large program could pick the same one. newunit= asks the runtime for a free unit and gets a negative number, which cannot clash with a number a program chose for itself.

A unit is closed automatically at the end of the program, and a unit left open when a procedure ends stays open, because units belong to the program and not to the scope. An explicit close is the way to say that the file is finished, and a program that writes a report should close it before it exits: the file is complete when the close returns.

Exercises

  1. Change status="replace" to status="old" in the first open of file_demo.f90 and run the program twice. What does the first run do?
  2. Open the same file twice at once and write to both units. Which order do the records land in?
  3. Inquire on a directory instead of a file. What does exist say?
  4. Write the four records with position="rewind" after the first open and print the file. Which record is replaced?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does status="replace" do when the file does not exist?

    Answer

    Creates it

    REPLACE creates the file when needed and truncates it otherwise.

  2. What does status="old" require?

    Answer

    That the file exists

    OLD is the status for reading an existing file.

  3. What does newunit=u give the program?

    Answer

    A free unit number that no other open in the program uses

    NEWUNIT asks the runtime for an unused unit.

  4. What does position="append" do?

    Answer

    Starts writing after the last record of the file

    Append puts the record pointer at the end.

  5. What does this program print? program p implicit none integer :: u logical :: there open (newunit=u, file="tmp_p.txt", status="replace", action="write") write (u, "(a)") "x" close (u) inquire (file="tmp_p.txt", exist=there) print *, there end program p

    Answer

    T

    The file was created by the write, so it exists.

  6. Which keyword promises that a program will only read a unit?

    Answer

    action="read"

    ACTION names what the program may do with the unit.

  7. What does inquire (file=name, size=n) return in n?

    Answer

    The size of the file in bytes

    SIZE is the size of the file on disk.

  8. When are units closed?

    Answer

    By CLOSE, or automatically at the end of the program

    Units belong to the program, not to the scope.

  9. What does a WRITE to a unit opened with action="read" do?

    Answer

    It is an error

    The action of the open forbids writing.

  10. What does a formatted WRITE to a unit put at the end of each record?

    Answer

    A line ending, so the next record starts on a new line

    Each formatted write is one record and ends with the line ending.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image