Internal files and parsing records
A record read from a file arrives as characters, and the program has to turn it into values. Fortran does that with an internal file: the record is a character variable and the same read statement parses it, either by splitting on blanks or by taking fixed columns. This lesson parses both ways, builds a record with the other direction of the same mechanism, and reports a line that does not fit.
Splitting a record by blanks
A list-directed read on a character variable works exactly like the one on a unit: it walks the record, takes a token for each item of the list, and converts it to the type of the variable. Blanks, commas and the end of the variable are the separators, so a record of three fields needs three variables.
The file parse.f90:
program parse_demo
implicit none
character(len=40) :: line
character(len=10) :: name
integer :: count
real :: price
line = "widget 12 3.50"
read (line, *) name, count, price
print *, "name : [", trim(name), "]"
print *, "count :", count
print *, "price :", price
end program parse_demo
gfortran -Wall -Wextra -std=f2018 parse.f90 -o parse
./parse
name : [widget]
count : 12
price : 3.50000000
The runs of blanks between the fields do not matter, which is what makes this parse so short: any number of blanks is one separator. The name arrives in a ten-character variable padded with blanks, so the program trims it for the print, and the two numbers become an integer and a real by the type of the variables and not by anything in the text.
Fixed columns
A record written by a program with a format has its fields at fixed columns, and a read of a substring takes them without any search. The expression line(1:6) is a section of the string, and an internal read of it with i6 parses six characters as an integer.
program columns_demo
implicit none
character(len=30) :: line
character(len=4) :: code
integer :: id
line = "000123ABCD"
read (line(1:6), '(i6)') id
code = line(7:10)
print *, "id :", id
print *, "code : [", code, "]"
end program columns_demo
gfortran -Wall -Wextra -std=f2018 columns.f90 -o columns
./columns
id : 123
code : [ABCD]
The identifier is a zero-padded number and the code is text, and the two come out of one record without a separator between them: the columns are the format. That is the parse to write when the file is a report the program itself produced, because the widths are known on both sides.
Building a record
The other direction is a write to the same variable. The program formats two values with a comma between them and reads the record back, which is the round trip a CSV file needs.
program record_demo
implicit none
character(len=40) :: rec
integer :: i
real :: x
write (rec, '(i4,a,f6.2)') 7, ",", 2.5
print '(a,a,a)', "record : [", trim(rec), "]"
read (rec, *) i, x
print *, "i =", i, " x =", x
end program record_demo
gfortran -Wall -Wextra -std=f2018 record.f90 -o record
./record
record : [ 7, 2.50]
i = 7 x = 2.50000000
The written record is nine characters: an integer in four columns, the comma, and the real in six. The list-directed read on the way back accepts the comma as a separator, so the same program both produces and consumes the line, and the values survive the trip.
A record that does not parse
A line from the outside world is not always the shape the program expected. The read of an internal file takes the same iostat and iomsg as a read of a unit, and the status is what lets a program skip a bad line instead of stopping.
program badparse_demo
implicit none
character(len=20) :: line
character(len=80) :: msg
integer :: ios, n
line = "12x"
msg = ""
n = 0
read (line, *, iostat=ios, iomsg=msg) n
print *, "ios :", ios
print *, "message : [", trim(msg), "]"
print *, "n :", n
end program badparse_demo
gfortran -Wall -Wextra -std=f2018 badparse.f90 -o badparse
./badparse
ios : 5010
message : [Bad integer for item 1 in list input]
n : 0
The status is positive and the target keeps the value it had, which is why the program sets it first. A parser that counts its bad lines prints this message with the line number and carries on, and a parser that must reject the whole file counts them and stops at the end.
Which parse to write
Use a list-directed read when the fields are separated by blanks or commas and the widths do not matter: it is one line and it accepts any spacing. Use fixed columns when the file is a table the program produced and the layout is part of the format: it is exact and it accepts a field with a blank in it. Use index and a substring when the separator is something the language does not treat as one, such as a semicolon, and read the pieces with the list-directed form.
The three codes fit in one small subroutine each, and the next lesson is where a parse becomes one.
Exercises
- Parse "alpha,12,3.5" with one list-directed read. Which characters act as the commas?
- Read the same line with a field that holds a blank, such as "New York". What do you need that a list-directed read does not give?
- Build a record of four values with an internal write and read it back into four variables. Which descriptor makes the fields fixed?
- Read line(1:6) as a real instead of an integer for a six-character field. What status comes back for the record above?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is an internal file?
Answer
A CHARACTER variable used as the unit of a read or write
The record lives in memory and the read parses it.
-
What does a list-directed read use as separators between fields?
Answer
Blanks, commas and the end of the record
The same rules as a list-directed read from a unit apply.
-
What does this program print?
program p implicit none character(len=30) :: line integer :: a, b line = "3 7" read (line, *) a, b print *, a + b end program pAnswer
10
The two numbers are parsed separately and added.
-
What does
read (line(1:6), "(i6)") iddo?Answer
Parses the first six characters as an integer
A substring is an internal file of that length.
-
What does
write (rec, "(i4,a,f6.2)") 7, ",", 2.5produce?Answer
An integer in four columns, a comma and a real in six
The descriptors decide the columns of the record.
-
What does the status of an internal read tell a program?
Answer
Whether the characters could be converted to the types of the list
A conversion failure is a positive status.
-
What happens to a variable whose field does not parse?
Answer
It keeps the value it had before the read
The transfer fails and does not assign.
-
When is a fixed-column read better than a list-directed one?
Answer
When the layout is known and a field may contain a blank
Columns separate fields that blanks cannot.
-
What is the result of
read ("12x", *) nfor an integer n?Answer
A positive status, because the record is not an integer
The trailing x makes the token invalid, as the page shows.
-
Which pair of statements turns a record into values and values into a record?
Answer
READ and WRITE on a CHARACTER variable
The internal file is the buffer both statements work on.
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev