Search code examples
loopsvariablesfortranfortran90do-loops

Reading data from variable input files in Fortran


I'm trying to read data from an input file (multiple files actually) and then perform certain operations on the data for each file and print the output of each input file to an output in Fortran,

So it's something like this..

Open (20, file="a0001.csv)
[perform operation on this file]
print output0001.txt

input files :a0001.csv,a0002.csv,...a0100.csv

outputfiles :output1.txt, output2.txt,.... output100.txt

I want to do this for about 100 files.

I'm thinking a do loop for 1-100 but I don't know how to loop through variable input files and then get an output per file


Solution

  • You can convert between numbers and their string representation with the read and write statements too. So I'd do something like this:

    character(len=len('a0001.csv')) :: infile
    character(len=len('output100.txt')) :: outfile
    
    do i = 1, 100
        write(infile, '("a", I4.4, ".csv")') i
        write(outfile, '("output", I0, ".txt")') i
    
        open(unit=20, file=infile, status="old", action="read", ...)
        open(unit=30, file=outfile, status="new", action="write", ...)
    
        !loop over contents of infile, write to outfile
    
        close(30)
        close(20)
    end do