Reading Files in Fortran

Our first program will demonstrate file reading operations in Fortran. Here’s the full source code:

program file_reading
  implicit none
  
  integer :: io_status, file_unit, num_bytes
  character(len=100) :: filename
  character(len=100) :: buffer
  
  ! Helper subroutine to check for errors
  subroutine check(status)
    integer, intent(in) :: status
    if (status /= 0) then
      print *, "Error occurred. Status:", status
      stop
    end if
  end subroutine check
  
  ! Set the filename
  filename = '/tmp/dat'
  
  ! Reading entire file contents
  open(newunit=file_unit, file=filename, status='old', action='read', iostat=io_status)
  call check(io_status)
  
  do
    read(file_unit, '(A)', iostat=io_status) buffer
    if (io_status /= 0) exit
    print *, trim(buffer)
  end do
  
  close(file_unit)
  
  ! Reading specific parts of the file
  open(newunit=file_unit, file=filename, status='old', action='read', iostat=io_status)
  call check(io_status)
  
  ! Read first 5 bytes
  read(file_unit, '(A5)', iostat=io_status) buffer
  call check(io_status)
  print '(A,A)', '5 bytes: ', buffer
  
  ! Seek to a specific position (6th byte) and read 2 bytes
  read(file_unit, '(A6)', advance='no', iostat=io_status)
  call check(io_status)
  read(file_unit, '(A2)', iostat=io_status) buffer
  call check(io_status)
  print '(A,A)', '2 bytes @ 6: ', buffer
  
  close(file_unit)
  
end program file_reading

This Fortran program demonstrates various file reading operations. Let’s break it down:

  1. We start by defining variables for file operations and a helper subroutine check to handle errors.

  2. The program first reads the entire contents of the file ‘/tmp/dat’ and prints it.

  3. Then, it demonstrates reading specific parts of the file:

    • Reading the first 5 bytes
    • Seeking to the 6th byte and reading 2 bytes
  4. Fortran doesn’t have built-in functions for some operations like Seek, so we use alternative methods like reading and discarding data to move the file pointer.

  5. Error checking is done after each file operation using the check subroutine.

To run the program, save it as file_reading.f90 and compile it using a Fortran compiler:

$ gfortran file_reading.f90 -o file_reading
$ ./file_reading

Make sure to create the ‘/tmp/dat’ file with some content before running the program:

$ echo "hello" > /tmp/dat
$ echo "fortran" >> /tmp/dat

This example demonstrates basic file reading operations in Fortran. While Fortran doesn’t have some of the more advanced file handling features of modern languages, it provides sufficient functionality for most file reading tasks.