What does READ()
do in Fortran?
For example:
READ(1,82)
This is sometimes called list directed read/write. read (*,*) list-of-variables write(*,*) list-of-variables. The first statement will read values from the standard input and assign the values to the variables in the variable list, while the second one writes to the standard output.
The READ statement updates the value of the associated FILE STATUS variable. A successful Format 1 READ statement retrieves a record from the file according to the following rules: The last OPEN, READ, or START verb used for the file determines which record is retrieved.
The READ statement is used to pick up information for input from external sources. These sources could be input from the keyboard, computer file or a magnetic tape. It can also be used to convert numbers represented within CHARACTER variables to a machine numerical representation (REAL, INTEGER, etc.).
A read/write variable means a variable to which you can assign some value and later on read the same eg var x = 10; writing to it console.
1 is the file handle, which you have to open with the proper open call. 82 is a label that references a format, meaning how you will report the data in terms of visual formatting.
program foo
implicit none
integer :: i
double precision :: a
write (*,*) 'give me an integer and a float'
read (*,82) i,a
write (*,82) i,a
82 format (I4, F8.3)
end program
In this example, the program accepts from the standard input (whose unit number is not specified, and so I put a *) an integer and a floating point value. the format says that the integer occupies the first four columns, then I have a float which stays in 8 columns, with 3 digits after the decimal point
If I run the program now, and I don't follow exactly this format, the program will complain and crash, because the first 4 columns are expected to represent an integer (due to the I4 format), and "5 3." is not a valid integer
$ ./a.out
give me an integer and a float
5 3.5
At line 7 of file test.f (Unit 5)
Traceback: not available, compile with -ftrace=frame or -ftrace=full
Fortran runtime error: Bad value during integer read
However, a correct specification (please note the three spaces before the number 5) will perform the correct operation (with a little tolerance, it's not that strict)
$ ./a.out
give me an integer and a float
5 3.5
5 3.500
$
It reads from "unit" (opened file) number 1, according to the FORMAT statement at label 82. However since the statement doesn't list any variables it has no place to put the data it's reading, which is unlikely to help; READ(1,82) FOOBAR
would more usefully put the data it's reading in variable FOOBAR.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With