Reading input from stdin

A program that reads what a person types reads unit five, the standard input, and it has to know when the input ends. Fortran answers with a status value rather than an exception: iostat is zero for a value read, negative for the end of the file and positive for a record that could not be converted. This lesson writes the loop that stops on any of them and shows how the three cases differ.

Numbers until the input ends

The pattern is a loop with no count: read one value, leave the loop when the status is not zero, and keep the running total. A program written this way never asks how many values there are, which is what makes it usable with a redirected file and with a terminal.

The file stdin.f90:

program stdin_demo implicit none integer :: ios, n real :: x, total n = 0 total = 0.0 do read (*, *, iostat=ios) x if (ios /= 0) exit n = n + 1 total = total + x end do print *, "read :", n print *, "total :", total if (n > 0) print *, "mean :", total / n end program stdin_demo

gfortran -Wall -Wextra -std=f2018 stdin.f90 -o stdin
printf '1.5\n2.5\n3.0\n' | ./stdin
./stdin < /dev/null

read : 3
total : 7.00000000
mean : 2.33333325
read : 0
total : 0.00000000

The first three lines are the three values of the pipe, and the last two are the same program with no input at all: it read nothing, summed nothing and did not divide by zero, because the mean is printed only when the count is positive. The printf writes the three numbers, one per line, and the shell connects them to the standard input.

End of file is a status, not a crash

Without iostat the same read would stop the program with an error at the end of the input. The status turns that into a value the program can test, and the test is ios /= 0 for "nothing more to read", not one exact number: the standard says nothing about which negative value an end of file reports.

A rough cast of the three cases is worth keeping in mind: zero means a value arrived, a negative status means the input ended, and a positive status means a record arrived but could not be converted. A program that must do something different for a bad record tests ios > 0 and reports the line.

Records until the input ends

Reading lines rather than numbers uses the (a) format, which takes the record as text and pads it to the length of the variable. The same status ends the loop, and the program keeps the longest line it saw.

program records_demo implicit none character(len=80) :: line, best integer :: ios, n, longest n = 0 longest = 0 best = "" do read (*, '(a)', iostat=ios) line if (ios /= 0) exit n = n + 1 if (len_trim(line) > longest) then longest = len_trim(line) best = line end if end do print *, "lines :", n print *, "longest :", longest print *, "text : [", trim(best), "]" end program records_demo

gfortran -Wall -Wextra -std=f2018 records.f90 -o records
printf 'alpha\nbeta gamma\ndelta\n' | ./records
./records < /dev/null

lines : 3
longest : 10
text : [beta gamma]
lines : 0
longest : 0
text : []

A record longer than eighty characters would be split into two reads, because a formatted read with (a) takes at most the length of its variable. A program that must keep a long line declares the buffer large enough for the longest record it accepts.

A value that is not a number

The positive status is the one a program that reads a file of numbers needs. The read below is from a character variable, so the page can show the bad record without a file, and iomsg carries the compiler description:

program badinput_demo implicit none character(len=40) :: line character(len=80) :: msg integer :: ios real :: x msg = "" x = -1.0 line = "not a number" read (line, *, iostat=ios, iomsg=msg) x print *, "ios :", ios print *, "message : [", trim(msg), "]" print *, "x :", x end program badinput_demo

gfortran -Wall -Wextra -std=f2018 badinput.f90 -o badinput
./badinput

ios : 5010
message : [Bad real number in item 1 of list input]
x : -1.00000000

The status is positive, the message names the item, and the target keeps the value it had: minus one, which the program set before the read. The number 5010 is this compiler and this error; another error has another number, so the test is the sign and never the value.

Exercises

  1. Feed the first program the line 1.5 two 3.0. How many values does it read, and what does the total become?
  2. Change the test to if (ios < 0) exit and feed the bad line. What happens, and why is the looser test dangerous?
  3. Count the words of every record in the second program with the word count of the string search lesson. What is the total?
  4. Print the line number with each record the second program reads. Which counter do you need?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does read (*, *, iostat=ios) x read?

    Answer

    One value from the standard input, with the status in ios

    Unit star is the standard input and the list-directed format reads one item.

  2. What does a negative IOSTAT mean?

    Answer

    The input ended

    An end of file condition reports a negative status.

  3. One read returns IOSTAT = -1 and another returns IOSTAT = 5010. What do the two statuses mean?

    Answer

    The first is an end of the input and the second a record that could not be converted

    A negative status is an end of file and a positive one is a conversion error.

  4. What does a positive IOSTAT mean?

    Answer

    A record arrived but could not be converted

    A conversion error is a positive status.

  5. What does the format (a) do on input?

    Answer

    Takes the record as text up to the length of the variable

    The a descriptor transfers characters and pads the variable.

  6. Why does the first program test n > 0 before printing the mean?

    Answer

    A division by a zero count is a division by zero

    With no input the count is zero, and dividing by it is an error.

  7. What does iomsg hold after a failed read?

    Answer

    A description of the error in words

    IOMSG receives the compiler message for the condition.

  8. Which unit number is the standard input?

    Answer

    5, or the star that means it

    Unit five is the preconnected input unit; star is its alias.

  9. What should a program compare the status against?

    Answer

    Zero, and the sign for the two kinds of failure

    The standard does not fix the numbers, only the sign.

  10. What happens to a program that reads stdin without IOSTAT at the end of the input?

    Answer

    It stops with an end of file error

    An unhandled end of file terminates the program with an error.

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

Banner image