next up previous contents
Next: Arrays Up: Input and Output Previous: Read and Write   Contents

Application

Modify the Fahrenheit to Celsius program to read the temperature () from one file, and output it to another file ().
program temp_conv
implicit none
  integer::i,n
  real::f,c
  integer::in=10,out=11  ! unit numbers 
  !open the files
  open(unit=in,file='fahr.data',action='read')
  open(unit=out,file='celsius.data',action='write')
  !read and write how many temperatures
  read(unit=in,fmt=*) n
  write(unit=out,fmt=*) n
  do i=1,n
    read(unit=in,fmt=*) f
    c=9.0/5.0*(f-32)
    write(unit=out,fmt=*) c
    print*,i,' F=',f,' is C=',c
  end do
end program temp_conv
\endlstlisting}

The open, close, read and write functions can be checked if they performed
ok using the IOSTAT parameter. In our case we check whether
end-of-file was reached and if so we exit the loop. This way there 
is no need to have the number of temperatures as the first number in the file.
%%
\begin{verbatim}
program temp_conv_3
implicit none
  real::f,c
  integer::iostatus
  !open the data file, F
  open(unit=10,file='fahr2.data',action='read',iostat=iostatus)
  !check if the file was opened properly
  if(iostatus.NE.0) then
    print*,'Data file could not be opened'
    stop ! terminates the program
  end if
  !open the result file
  open(unit=11,file='celsius2.data',action='write',iostat=iostatus)
  !check if the file opened properly
  if(iostatus.NE.0) then
    print*,'Output file cannot be opened'
    stop
  end if
  do
    read(unit=10,fmt=*,iostat=iostatus) f
    !check if this is a valid read
    if(iostatus.NE.0) then
      print*,'end of file reached'
      exit
    end if
    c=5.0/9.0*(f-32)
    write(unit=11,fmt=*) c
  end do
end program temp_conv_3



Adrian Sandu 2001-08-26