loopsfortran

Opening external data files under Fortran do loop


The command to create a new data file or to read an already created data file in Fortran is easy.

For example, open(12, file='new.dat', action='write'/'read').

But I want to do this inside a loop. Because, say I have to create 500 different data files and also read them later on. So it is very cumbersome to perform manually.

But I don't know if it can be done using this simple way at all. I think it is mainly because of the way Fortran names the files, e.g. 'new.dat' above. Inside a loop it can not, by itself, generate files continuously through assigning names to them.

I tried the following:

program test_file_opening

implicit none

!real ::
integer :: i

do i = 1, 10
 open(i, file='i.dat', action='write')
end do

do i = 1, 10
 write(i,*) 'hallo world!'
end do

end program

As expected, i is within quotation, and just one data file gets created, with only the single line text hallo world! in it.

Is there any way to create a lots of external data files (with entries specified in the code) under 'do loop' in Fortran?


Solution

  • This one generates 10 .dat files with "Hello world!" in them:

     program test_file_opening
    
        implicit none
    
        !real ::
        integer :: i, ios
        character(len=10) :: filename
    
        do i = 1, 10
            write(filename, '(I0)') i
            filename = trim(adjustl(filename)) // '.dat'
    
            open(i, file=filename, status='new', iostat=ios)
    
            if (ios /= 0) then
                print *, 'Error opening file ', filename
            else
                write(i, *) 'Hello World! ', i
                close(i)
            end if
    
        end do
    
    end program
    

    looks much longer, but write(filename, '(I0)') i converts the integer i to a string and writes it to filename, after that filename = trim(adjustl(filename)) // '.dat' appends .dat to the integer string.