Shahram Maghami
Shahram Maghami

Reputation: 7

How to open all files with some specific extension(prefix in name) in fortran ?

I want to read data from some files in Fortran, I can do that when the file names have a regular order. but now it's not regular, although all have same prefix for example : Fix001, Fix002, Fix023, Fix432, ...

I want the program get the prefix from the user and open all the files in a loop, read the data and write them in a single file. any idea ? Thanks.

PROGRAM Output
Implicit none
Integer ::n=5        !number of files
Integer ::nn=50  !number of rows in each file
Integer ::i,j
Real,Dimension(:),Allocatable::t,x,y,z
Character(len=12)::TD 

Open(11,file='outputX.txt')
Allocate (t(1000),x(1000),y(1000),z(1000)) 

 j=0
Do i=1,n
    Write(TD,10)i 
    Write(*,*)TD 
    Open(1,file=TD) 
        Read(1,*)(t(j),x(j),j=1,nn)
        Write(11,20)(x(j),j=1,nn)
 j=j+1
Enddo

10  Format('100',i3.3,'') 
20 Format(<nn>E25.8E3)

 Deallocate(x,y,z,t) 
 END PROGRAM Output

Upvotes: 0

Views: 1343

Answers (1)

chw21
chw21

Reputation: 8140

If you do have an upper limit, you can try to open the file and test with the iostat parameter whether that was successful. If it wasn't, you skip the file.

This is an example that reads only the first integer variable from a file and appends it to the output file:

program read_files
    implicit none
    integer :: i, d
    integer :: ioerr
    character(len=len("FixXXX.txt")) :: fname

    open(unit=30, file="Output.txt", action="write", iostat=ioerr)
    if (ioerr /= 0) stop 1

    do i = 0, 999
        write(fname, '(A, I3.3, A)') "Fix", i, ".txt"
        open(unit = 40, file=fname, status="old", action="read", iostat=ioerr)
        if (ioerr /= 0) cycle
        read(40, *) d
        write(30, *) d
        close(40)
    end do
end program read_files

Upvotes: 2

Related Questions