Reading Files in Co-array Fortran

Our first example demonstrates how to read files in Co-array Fortran. Reading files is a basic task needed for many programs. Let’s look at several ways to read files.

program read_files
  use iso_fortran_env
  implicit none

  character(len=100) :: filename = '/tmp/dat'
  integer :: unit, io_status
  character(len=100) :: buffer
  integer :: bytes_read
  
  ! Read entire file contents
  call read_entire_file(filename)

  ! Open the file for reading
  open(newunit=unit, file=filename, status='old', action='read', iostat=io_status)
  if (io_status /= 0) then
    print *, "Error opening file"
    stop
  end if

  ! Read first 5 bytes
  read(unit, '(A5)', advance='no', iostat=io_status) buffer
  if (io_status == 0) then
    print '(A,A)', "5 bytes: ", buffer
  end if

  ! Seek to a specific position and read
  read(unit, '(A)', pos=7) buffer
  print '(A,A)', "2 bytes @ 6: ", buffer(1:2)

  ! Read using inquire for more control
  inquire(unit, pos=current_pos)
  read(unit, '(A)', pos=current_pos+5) buffer
  print '(A,A)', "Next 2 bytes: ", buffer(1:2)

  ! Use internal read for parsing
  buffer = "12345"
  read(buffer, *) bytes_read
  print '(A,I0)', "Parsed number: ", bytes_read

  ! Close the file
  close(unit)

contains

  subroutine read_entire_file(filename)
    character(len=*), intent(in) :: filename
    integer :: unit, io_status
    character(len=1000) :: content

    open(newunit=unit, file=filename, status='old', action='read', iostat=io_status)
    if (io_status /= 0) then
      print *, "Error opening file"
      return
    end if

    read(unit, '(A)', iostat=io_status) content
    if (io_status == 0) then
      print *, trim(content)
    end if

    close(unit)
  end subroutine read_entire_file

end program read_files

This program demonstrates various file reading operations in Co-array Fortran:

  1. We start by reading the entire contents of a file using a subroutine read_entire_file.

  2. Then we open the file and perform several read operations:

    • Read the first 5 bytes.
    • Seek to a specific position (7th byte) and read from there.
    • Use inquire to get the current position and read from a relative position.
  3. We also demonstrate using internal read for parsing string data.

  4. Finally, we close the file.

To run the program, compile it and execute:

$ gfortran -coarray=single read_files.f90 -o read_files
$ echo "hello" > /tmp/dat
$ echo "fortran" >> /tmp/dat
$ ./read_files
hello
fortran
5 bytes: hello
2 bytes @ 6: fo
Next 2 bytes: tr
Parsed number: 12345

This example showcases basic file operations in Co-array Fortran. While Co-array Fortran doesn’t have exact equivalents for all Go features (like bufio), it provides robust file I/O capabilities through standard Fortran procedures.