Warm tip: This article is reproduced from serverfault.com, please click

reading different files from the subroutine depending on the input

发布于 2020-11-28 02:52:29

I have a piece of code in fortran. I have the files dumped in subroutine. Now I want to call the specific file from the subroutine which depends on m. for eg if m=3 it should read filename(3) and if m=6 it should read filename(6). It is simply not working. Can somebody help me to fix this?

Program main
implicit none
integer,parameter :: dp=kind(1.d0)
real,parameter::m=3
real(dp), dimension(:,:), allocatable :: s

 call My_Reader(m) 
 allocate (s(m,m))
 read(m*10,*) s
 print*,s

 SUBROUTINE My_Reader(m)
 integer,parameter :: dp=kind(1.d0)
 character (len=256)::filename(m)
 integer , intent(in) :: m
 filename(6)='C:\Users\spaudel\Documents\S6.txt'
 filename(3)='C:\Users\spaudel\Documents\S3.txt'
 OPEN (unit=m*10,FILE=fileName(m),status='old', action='read')
 END SUBROUTINE My_Reader

in the above program it should print s( my filename is m*m matrix) but sometimes it prints sometimes not. I am using gfortran.

Questioner
user13826174
Viewed
0
chw21 2020-11-28 13:24:54

The length of the filename array is given as (m), which is the dummy argument for which of the files you want to read.

So if, for example, you call My_Reader(3), it will only initialize a 3-element array for filename and then anything can happen when you write something to the 6th element.

You could simply fix the size of the filename array in the subroutine declaration block:

character(len=256) :: filename(6)

but I would do something completely different, I'd use a select case to assign the filename in the subroutine:

subroutine my_reader(m)
    integer, intent(in) :: m
    character(len=256) :: filename

    select case (m)
        case(3)
            filename = 'C:\Users\spaudel\Documents\S3.txt'
        case(6)
            filename = 'C:\Users\spaudel\Documents\S6.txt'
        case default
            print *, 'incorrect selection of file number: `, m
            STOP
    end select

    open(unit=m*10, file=filename, ...)
end subroutine my_reader