UNIHIVE

Study Hub UNIPORT ENG 213.1

ENG 213.1 · Computer Programming for Engineers

Reading and writing data files

OPEN, READ, WRITE and CLOSE with unit numbers, end-of-file checks and file formats for lab data.

Our notes

1 min read

Why files

Lab readings, design tables and results are often too long to type each time. Programs read input files and write result files that a spreadsheet or plotting tool can open.

Opening and closing

open(unit=10, file='readings.txt', status='old', action='read')
open(unit=20, file='results.txt', status='replace', action='write')
...
close(10)
close(20)

  • unit is a number (avoid 5 and 6, which are often the keyboard and screen).
  • status: 'old' (must exist), 'new' (must not exist), 'replace', 'unknown'.

Reading until the end of the file

integer :: ios, n
real :: t, p
n = 0
do
  read(10, *, iostat=ios) t, p
  if (ios /= 0) exit
  n = n + 1
end do
iostat is 0 on success, negative at end of file, positive on an error. Checking it stops the program crashing at the end of the data.

Writing results

write(20, '(F8.2, 2X, F10.3)') t, p
A comma-separated file opens neatly in a spreadsheet:
write(20, '(F8.2, A, F10.3)') t, ',', p

Worked example: heat loss through walls

A file walls.txt has one wall per line: thermal conductivity k (W/m·K), area A (m²), temperature difference ΔT (K), thickness L (m). The program reads each line and writes Q = kAΔT/L.
Line "0.8 10.0 20.0 0.2" gives Q = 0.8 × 10 × 20 / 0.2 = 800 W.
Line "0.04 10.0 20.0 0.05" (insulation) gives Q = 0.04 × 10 × 20 / 0.05 = 160 W.

Good habits

  • Put a header line in result files saying what each column is, with units.
  • Check iostat on OPEN as well (a missing file).
  • Close files when done.

Exams usually ask

  • Write statements to open, read from and write to a file.
  • Explain the use of iostat and end-of-file detection.

Common mistake

Opening an input file with status='replace', which wipes it. Use 'old' for files you read.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All ENG 213.1 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.