tags:

views:

961

answers:

1

I have a program in Fortran that saves the results to a file. At the moment I open the file using

OPEN (1, FILE = 'Output.TXT')

However, I now want to run a loop, and save the results of each iteration to the files 'Output1.TXT', 'Output2.TXT', 'Output3.txt', ...

Is there an easy way in Fortran to constuct filenames from the loop counter i?

+4  A: 

you can write to a unit, but you can also write to a string

program foo
    character(len=1024) :: filename

    write (filename, "(A5,I2)") "hello", 10

    print *, trim(filename)
end program

Please note (this is the second trick I was talking about) that you can also build a format string programmatically.

program foo

    character(len=1024) :: filename
    character(len=1024) :: format_string
    integer :: i

    do i=1, 10
        if (i < 10) then
            format_string = "(A5,I1)"
        else
            format_string = "(A5,I2)"
        endif

        write (filename,format_string) "hello", i
        print *, trim(filename)
    enddo

end program
Stefano Borini
Two comments: - you don't have to discriminate on the value of I; the format (I0) will output an integer without any space; also, if you want a fixed width and padding with zeroes (like "output001.txt"), you need to used (I0.3) - the format (A5I2) is not valid Fortran according to any norm, as format specifiers are to be separated by commas: (A5,I2)
FX
Well, it was for educational purposes, not intended to be the solution. In general I use the padding zeros (as it sorts nicely), but the I0 thingie I didn't know about. Thanks!! (fixed the commas, I think my style was the old one, still accepted)
Stefano Borini