So far we have assumed that the input/output has been to the standard input or the standard output. It is also possible to read or write from files that are stored on some external storage device, typically a disk (hard disk, floppy) or a tape. In FORTRAN each file is associated with a unit number, an integer between 1 and 99. Some unit numbers are reserved: 5 is standard input, 6 is standard output.
Opening and closing a file
Before you can use a file you have to open it. The command is
Where the most common specifies are:
UNIT = associate unit number
FILE = file name
ACCESS = data input mode
STATUS = file type � Old or New
Instead of using two CONTINUE statements you can use one.
UNIT number is a number in the range 1-99 that denotes this file (the programmer may chose any number but he/she has to make sure it is unique).
FILE is a character string denoting the file name.
ACCESS a character expression that evaluates to 'APPEND', 'DIRECT', or 'SEQUENTIAL' (the default).
STATUS is a character string that has to be either NEW, OLD or SCRATCH. It shows the prior status of the file. A scrath file is a file that is created and deleted when the file is closed (or the program ends). After a file has been opened, you can access it by read and write statements.
When you are done with the file, it should be closed by the statement
Read and write revisited
he only necessary change from our previous simplified READ/WRITE statements, is that the unit number must be specified.
READ(UNIT,*) variable to read data
C Create an external data file OPEN (7, FILE = 'DATA01.TXT', ACCESS = 'APPEND',STATUS = 'NEW') C Write some values to the file DO 10 I=1,100 WRITE(7,*) I 10 CONTINUE C Close the external file CLOSE(7) STOP END
c Create an external data file c Now writing data, 10 numbers per line OPEN (7, FILE = 'DATA02.TXT', ACCESS = 'APPEND',STATUS = 'NEW') C Write some values to the file DO 10 I=1,10 WRITE(7,20) (J,J=1+(I-1)*10,I*10) 10 CONTINUE 20 FORMAT(10I4) C Close the external file CLOSE(7) STOP END
C Simultaneously handle two files. One file used to read C the data and another file to write the modified data. DIMENSION IDATA(100) C Open the file to write data OPEN (7, FILE = 'DATA03.TXT', ACCESS = 'APPEND',STATUS = 'NEW') C Open file for read data OPEN (8, FILE = 'DATA01.TXT') WRITE(7,*) 'Here is the data' ISUM=0 DO 10 I=1,100 READ(8,*) IDATA(I) ISUM=ISUM+IDATA(I) WRITE(7,*) IDATA(I) 10 CONTINUE C Close read file CLOSE(8) WRITE(7,*) '-------------------------------' WRITE(7,15) ISUM C Float will convert Integer into Real WRITE(7,20) FLOAT(ISUM)/100 15 FORMAT(' Summation = ',I4) 20 FORMAT(' Average = ',F7.2) CLOSE(7) STOP END