Fortran Wiki
sequential_filenames

Generating sequentially numbered output files

To create numbered file names such as out_1.txt, out_2.txt, … use an internal write of an INTEGER value. This extended example generates sequentially numbered files and then deletes them :

program demo_sequential_filenames
implicit none
integer :: num, iostat, lun
character(len=:), allocatable :: prefix, suffix
character(len=4096) :: filename, iomsg
character(len=*),parameter :: all='(*(g0))'
   prefix = 'out_'
   suffix = '.txt'
   do lun = 10, 12 ! create filenames matching unit numbers
     !
      write (filename, fmt='(a, i0, a)') prefix, lun, suffix
     !
     ! open a new formatted file for writing
      open (unit=lun, file=filename, form='formatted', &
      & action='write', status='new', access='sequential', &
      & iostat=iostat, iomsg=iomsg)
     !
     ! check the open for errors
      if (iostat /= 0) then
         print all, '<error>cannot open file ', trim(filename), &
         & ':', trim(iomsg)
         stop 1
      else
         print all, 'opened file ', trim(filename), ' on unit ', lun
      end if
   end do
  !
  ! clean up the debris from the example program
  !
   do lun = 10, 12
      close (unit=lun, status='delete', iostat=iostat, iomsg=iomsg)
      if (iostat /= 0) then
         print all, '<error>did not clean up ', trim(filename), &
         & ':', trim(iomsg)
      else
         print all, 'closed unit ', lun
      end if
   end do

end program demo_sequential_filenames

output :

opened file out_10.txt on unit 10
opened file out_11.txt on unit 11
opened file out_12.txt on unit 12
closed unit 10
closed unit 11
closed unit 12