Ask Your Question
1

How can I repeatedly read from a Fortran input file without having to close it every time?

asked 2021-08-15 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-02-07 18:00:00 +0000

qstack gravatar image

You can use the Fortran rewind statement to reset the file pointer to the beginning of the file, allowing you to reread the file without having to close and reopen it. Here's an example code snippet that demonstrates how to do this:

program read_file
  implicit none
  integer :: unit, i
  real :: x

  ! Open input file
  open(unit = 10, file = "input.txt", status = "old", action = "read")

  ! Read data from file
  do i = 1, 10
     read(10,*) x
     print*, x
  end do

  ! Rewind file pointer back to beginning
  rewind(10)

  ! Read data from file again
  do i = 1, 10
     read(10,*) x
     print*, x
  end do

  ! Close input file
  close(unit = 10)
end program read_file

In this code, we first open the input file and read the data from it using a do loop. After that, we use the rewind statement to reset the file pointer back to the beginning of the file, and then we read the data from the file again using another do loop.

Note that the rewind statement can only be used with files that were opened in read mode (action = "read"). If you opened the file in write mode (action = "write"), you will need to close and reopen the file to start writing from the beginning again.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-15 11:00:00 +0000

Seen: 9 times

Last updated: Feb 07 '22