1

I want to read in multiple files in Fortran in a loop by using the filename formatting system. Problem is the filenames have numbers that don't follow each other directly. Examples of the filenames are 4e3_2048_380_40_3e9.ksz_cl.txt, 4e3_2048_200_80_2e8.ksz_cl.txt. The 3rd, 4th and 5th numbers in the filenames form a 3x3 grid. The first number goes from 140-260, the second goes from 40-80 and the third number goes from 2e8-2e9.

I've searched for answers in threads like reading multiple files in fortran but it doesn't seem to answer my question. My code below currently print out 4e3_2048_01.ksz_cl.txt.

program readfiles
implicit none
integer :: i, N
Logical, Save :: first_time = .True.
CHARACTER(len=25) :: FN 
N=3 !--arbitrary number of files 

if(first_time) then
DO I=1,N
WRITE(FN,10)I
WRITE(6,*)FN 
OPEN(1,FILE=FN, status='replace') 
CLOSE(1)
END DO 
10 FORMAT('4e3_2048_',I2.2,'.ksz_cl.txt') 
endif


end program readfiles
Ian Bush
  • 6,996
  • 1
  • 21
  • 27
user9404237
  • 149
  • 8
  • 3
    While it would certainly be possible to come up with a scheme that would do this, this is complicated enough that you may want to look at simply reading a directory contents. – Dan Sp. Aug 26 '19 at 23:08
  • 3
    Or simpler add a file that contains the list of files you want to read – Ian Bush Aug 27 '19 at 08:45
  • 1
    Possibly useful: https://stackoverflow.com/questions/1262695/convert-integers-to-strings-to-create-output-filenames-at-run-time – High Performance Mark Aug 27 '19 at 09:54
  • 2
    How did you generate those files? You could use the same tool (the logic of creating the filenames) to generate a list of files to read, possibly also containing the relevant parameters (grid index or parameter values). – Pierre de Buyl Aug 27 '19 at 10:49
  • What is the stride between those numbers? For example, there are 900,000,000 whole numbers between 1e8-1e9. Do you really have that many external files? Depending on your answer, you can loop over all three-numbers possibilities, then `inquire()` the existence of such file, and if it exists, read it. – Scientist Aug 29 '19 at 16:39

0 Answers0