Opening and Closing Files
Every file operation in Fortran starts with OPEN, which associates a file on disk with an integer unit number and specifies access details: OPEN(UNIT=10, FILE='data.txt', STATUS='old', ACTION='read', IOSTAT=ios) opens an existing file for reading, checking IOSTAT afterward to confirm success (zero means no error). STATUS can be 'old' (must already exist), 'new' (must not already exist), 'replace' (overwrite or create), or 'unknown'. When done, CLOSE(UNIT=10) releases the unit and flushes any buffered writes to disk; forgetting to close a file can leave data unwritten if the program terminates abnormally.
Cricket analogy: Checking a stadium gate is unlocked and correctly assigned before letting the ground crew in mirrors OPEN verifying STATUS='old' and reporting IOSTAT if the file doesn't exist.
Reading and Writing Records
Once open, READ(10, '(...)') var_list reads a formatted record from unit 10 and WRITE(10, '(...)') var_list writes one, using the same edit descriptors as console I/O. List-directed I/O with an asterisk format, READ(10, *) a, b, c, lets Fortran auto-detect field boundaries from whitespace or commas, which is more forgiving than fixed-column formatted reads for irregularly spaced input. The special IOSTAT value returned by READ becomes negative at end-of-file, which is the idiomatic way to loop through an unknown number of records: DO; READ(10, *, IOSTAT=ios) x; IF (ios /= 0) EXIT; ... END DO.
Cricket analogy: Reading a ball-by-ball CSV log entry by entry until reaching the last delivery, checking for an end-of-innings marker each time, mirrors looping READ with IOSTAT until end-of-file is signaled.
Unit Numbers and NEWUNIT
Older Fortran code hardcodes small integer unit numbers like 10 or 20, which risks collisions if two parts of a program pick the same number for different files. Modern Fortran's NEWUNIT specifier avoids this entirely: OPEN(NEWUNIT=my_unit, FILE='log.txt', STATUS='replace') asks the runtime to allocate a guaranteed-unique unit number and stores it in the integer variable my_unit, which is then used for all subsequent READ/WRITE/CLOSE calls on that file, removing an entire class of bugs where two OPEN statements accidentally share a unit.
Cricket analogy: Assigning locker numbers to two different teams sharing a stadium, where a fixed number like 'locker 7' risks double-booking, mirrors hardcoded unit numbers colliding, while an attendant assigning the next free locker mirrors NEWUNIT.
Unformatted and Sequential Access
For performance-critical or large binary data, FORM='unformatted' writes raw binary bytes instead of human-readable text, avoiding the CPU cost of number-to-text conversion and producing smaller files, at the cost of not being human-readable or portable across compilers with different binary layouts. ACCESS='sequential' (the default) requires reading records in order from the start, while ACCESS='direct' with a fixed RECL (record length) lets a program jump straight to any record by number, useful for large datasets like a lookup table where random access by index is needed instead of scanning from the beginning each time.
Cricket analogy: Storing raw ball-tracking sensor data in a compact binary log rather than a readable text file mirrors FORM='unformatted' trading human readability for speed and smaller size.
program file_io_demo
implicit none
integer :: unit_out, unit_in, ios
integer :: id
real :: score
character(len=30) :: name
! Write a small formatted data file
open(newunit=unit_out, file='scores.txt', status='replace', action='write')
write(unit_out, '(A, I5, F8.2)') 'Alice', 101, 92.50
write(unit_out, '(A, I5, F8.2)') 'Bob', 102, 87.25
close(unit_out)
! Read it back, looping until end-of-file
open(newunit=unit_in, file='scores.txt', status='old', action='read', iostat=ios)
if (ios /= 0) then
print *, 'Could not open scores.txt'
stop 1
end if
do
read(unit_in, '(A10, I5, F8.2)', iostat=ios) name, id, score
if (ios /= 0) exit ! end of file or read error
print *, trim(name), id, score
end do
close(unit_in)
end program file_io_demoIOSTAT returns 0 on success, a negative value at end-of-file, and a positive value for an actual error (such as a malformed record). Always check IOSTAT rather than assuming a READ succeeded, especially when looping through a file of unknown length.
- OPEN associates a file with a unit number; STATUS controls whether the file must already exist, must not exist, or is replaced.
- CLOSE releases a unit and flushes buffered writes; always close files explicitly rather than relying on program termination.
- IOSTAT is 0 on success, negative at end-of-file, and positive on a genuine read/write error.
- NEWUNIT lets the runtime assign a guaranteed-unique unit number, avoiding manual unit-number collisions.
- List-directed I/O (format '*') tolerates irregular whitespace, unlike fixed-column formatted reads.
- FORM='unformatted' writes raw binary data, faster and more compact but not human-readable or portable.
- ACCESS='direct' with RECL enables random access to any record by number instead of sequential scanning.
Practice what you learned
1. What does STATUS='old' require when opening a file?
2. What value does IOSTAT typically return at end-of-file during a READ?
3. What is the main advantage of NEWUNIT over specifying a hardcoded UNIT number?
4. What does FORM='unformatted' mean for a file?
5. What does ACCESS='direct' combined with RECL enable?
Was this page helpful?
You May Also Like
Formatted I/O
How Fortran's FORMAT edit descriptors give precise, column-aligned control over how numbers and text are printed and read.
Intrinsic Functions
The built-in numeric, array, and character functions Fortran provides out of the box, from SQRT and MOD to SUM, MAXVAL, and TRIM.
Array Operations and Slicing
Whole-array arithmetic, array sections, and the WHERE/FORALL constructs that let Fortran express vectorized operations without explicit loops.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics