Reading a file only once

is there any simple way to open a file , read & write all its contents to the screen in fortran 77 but the problem it you need to read the file only once

I haven’t used Fortran 77, but I have a Fortran 90 code that seems to do the trick:

program main

    print *, read_whole_file("main.f90")


    !> read the file as a string
    function read_whole_file(file) result(string)
        character(*), intent(in) :: file        !! file name to read
        character(:), allocatable :: string     !! file content
        integer :: iunit, len

        open (newunit=iunit, file=file, status='old', action='read', access='stream', form='unformatted')

        inquire (iunit, size=len)
        allocate (character(len=len) :: string)
        read (iunit) string  ! use binary read to read the whole file faster

        close (iunit)

    end function read_whole_file

end program main

To compile and run the code:

gfortran main.f90 && ./a.out
1 Like

I haven’t used F77 for a long time, so I don’t have an exact code right now.

But you would need to:

  1. Create a string variable line as a large array of characters.
  2. Iterate through the file till you reach the end of file,
  3. At each line, read each line into the line variable
  4. Print the line variable to screen immediately after reading it.

Some helpful resources:

  1. How to read till end of file in F77 using END label specifier: io - How to know that we reached EOF in Fortran 77? - Stack Overflow
  2. How to create and set character arrays / strings in F77: Character String Assignment (FORTRAN 77 Language Reference)

For a general file, the short answer is no. In f77, there is no way to determine the length of each record. If you know the lengths of each record, or if all the records are the same length, then yes, you can read and write the file. But for a general file, with records of unknown length, f77 is not flexible enough to accomplish the task.

The task is possible in modern fortran. In fact, there are several ways: one character at a time, or even the whole file at once. The new features that can be used to accomplish this, that were not part of f77, include nonadvancing i/o and stream access.

Although I realize you might or might not have a choice, any code written in Fortran 77 is dead code. I advise to check out at least Fortran 2018 for any new developement. :slight_smile:

I accomplish this task with the following couple of procedures, but note I believe it uses a few features that were not available in F77.