Disk
I/O
References: Section
10 Fortran95
Manual and the Fortran
Lecture5
In READ/WRITE statements,
unit can be an integer number, which is assigned to a file by using the
OPEN statement. The general form for disk I/O is:
OPEN ( [UNIT=]
unit, FILE = file_name [,
specifiers])
READ ( unit, format [, options] ) variable_list
WRITE ( unit, format [, options] ) list
CLOSE ( [UNIT=] unit [, STATUS = status])
For example, the following program read real numbers from keyboard and
save those numbers in file fred.DAT (fred.DAT is a new file, which doesn’t exit on the
disk).
PROGRAM
NEWDATAFILE
OPEN (UNIT=14,FILE=’fred.DAT’,
STATUS=’NEW’)
! open fred.DAT and
link it to unit=14
WRITE (*,*) ‘ TYPE IN A
LIST OF REAL NUMBERS,ENDING WITH A LETTER’
100 READ
(*,1000,ERR=101)X !
input from keyboard
WRITE (*,1000) X
! output to monitor screen
WRITE (14,1000) X
! output to fred.DAT
GOTO
100
101 CLOSE(14)
! close fred.DAT
1000
FORMAT (F12.3)
END
Exercises
1) A unit number is an integer number. What
is the range of the unit number?
2) What will
happen, if fred.DAT already exists on the
disk?
3) (optional) Write a program (fred_r.f95) to read data
from fred.DAT and calculate the sum of all the
numbers.
4) Use a
text editor to create a data file (input.dat)
containing the following 10 numbers.
0.96 0.95 9.51 9.54 10.10
11.45 0.95 12.34 31.4 11.08
'input.dat' should have 10 lines with one data on each
line.
Write a program (diskIO.f95) to read data in 'input.dat' and find out how many numbers are below the average among the 10 numbers. Print the result on the screen.
Sort the 10 numbers in numerical order starting with the smallest and save the sorted 10 numbers onto a file (output.dat).