FORTRAN 90+: FILE INPUT AND OUTPUT
Fortran has the ability to write and read files, tape, printers and the terminal. The basic format for file input and output (also known as I/O) is
WRITE(unit number, format, options) var1, var2,... READ(unit number, format, options) var1, var2,...
The unit number describes where the information will be read from or written to. The unit number is an INTEGER that is associated to a file name in the OPEN statement. The format details are described in a separate section named Format. The options statement allows for output describing the status of the statement.
OPEN
The OPEN statement is used to call and prepare a file to be used. The basic format for an OPEN statement is
OPEN (unit= number, file=’file_name’, status=’choice_here’, options)
The unit, as described above, is how the file is referenced in READ, WRITE statements. The file name is used to give the new file a name or tell the program which file to read. The file name should include the path to that files location. The options for status are old, new, unknown. If a file already exists then it mustbe declared as old so the program does not try and create a new file with the same name. A new file is declared as new so the program does not try and find an existing file of the same name to edit or read. The final spot is for options. Here the file can be marked as read only, preventing any accidental changes to the file. Two example OPEN statements are
OPEN(unit=10, file=’/home/usr/Documents/hw.txt’, status=’new’) OPEN(unit=10, file=’/home/usr/Documents/data.txt’, & & status=’old’, readonly)
READ AND WRITE
Options are used to tell the user the status of the statement. The three options are
- END = label: Specifies a label to jump to if an END_OF_FILE (EOF) is reached
- ERR = label: Specifies a label to jump to if an error is encuntered in the I/O.
- IOSTAT = Integer_var: returns a positive, negative or zero value.
For IOSTAT, the values returned are
Zero means there was no error in reading.
Negative means the end-of-file mark was read, signifying the end of the input data file.
Positive means there was an error during the execution and gives the type of error based on what the number is.
To use the READ or WRITE functions on a variable, one should replace the location of the unit number with the variable name. New variables can not be initiated this way if the IMPLICIT NONE statement is used but it is useful to format CHARACTER strings. An even more important use is to convert strings to INTEGER or REAL or back again by reading a CHARACTER variable into INTEGER variables or by writing INTEGER values into a CHARACTER variable. For example,
CHARACTER(LEN=40) :: line INTEGER :: a,b,c line="123 67 89 1 3" READ(line,"(BZ,3I5)") a,b,c
This will output:
a= 12300 b= 67089 c= 1030
Another example to illustrate file I/O is
CHARACTER(LEN=40) :: line INTEGER :: a=12, b=13, c=5 WRITE(line,"(1x, SP, I3, T10, 2I3)" a, b, c
This will output
line= ’ +012 +13 +05’