Files

Open with newunit

Open connects a variable to a file: newunit hands you a free unit number, file names the path, and status replace starts fresh.

Action write locks in your intent, so a later accidental read fails loudly instead of corrupting data.

program openfile implicit none integer :: u open(newunit=u, file="nums.txt", status="replace", action="write") write(u, *) 42 close(u) end program openfile

Read records

Reading mirrors writing: open with status old and action read, pull values with a matching read list, then close.

Status old demands that the file exists, which catches typos in the name before any data moves.

program readrec implicit none integer :: u integer :: n open(newunit=u, file="nums.txt", status="old", action="read") read(u, *) n close(u) print *, n end program readrec

./readrec

42

Write records

Formatted writes control each record: one write statement produces one line, and the format sets its look.

Here a loop writes 1, 2, and 3 on separate lines, each in a field three wide.

program writerec implicit none integer :: u integer :: i open(newunit=u, file="count.txt", status="replace", action="write") do i = 1, 3 write(u, "(I3)") i end do close(u) end program writerec

cat count.txt

1
2
3

Close and status

Close releases the unit, and its status decides the fate of the file: keep saves it while delete removes a scratch file at once.

Always close what you open: open units block other access, and unwritten buffers may never reach the disk.

program closestat implicit none integer :: u open(newunit=u, file="temp.txt", status="replace", action="write") write(u, *) "done" close(u, status="keep") end program closestat

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image