Fortran; looping over file names with common attributes

烈酒焚心 提交于 2020-01-15 10:37:08

问题


I'm fairly new to Fortran and I am having trouble with my file names, I have a bunch of data in simuln#.res (where 1<#<20), I have multiple different directories with all the same simuln#.res names but they had different input parameters. The code looks like this:

  character(len=11) :: theFileA
  character(len=12) :: theFileB
  character(len=:), allocatable :: fileplace

  write(*,*) "the directory with the data sets, use quotations"
  read(*,*) fileplace

  fileLoop : do j=1,20
  if (j .lt. 10) then 
    write(theFileA, '("simuln", I1,".res")' ) j   
    open(newunit= iin,file = fileplace//theFileA,status='old')
 else 
    write(theFileB, '("simuln",I2,".res")') j
    open(newunit= iin,file = fileplace//theFileB,status='old')
 end if

does some stuff with the file 
end do fileLoop

The code compiles with a gfortran compiler on my mac, but when I put in my path to the directory with the files, it gives the error simuln1.res does not exist (which it absolutely does, triple checked). I have tried changing the edit descriptor (and making real(j)), but I still get the same thing. Can anyone help me?


回答1:


You have fileplace of deferred length ((len=:)), but you appear to not allocate it before attempting the read.

That is, read(*,*) fileplace doesn't, under the F2003 rules of automatic allocation, allocate fileplace to the correct length and assign. That means that later on fileplace could well be being treated as a zero-length character variable ('') in the file to be opened.

To check this hypothesis, try print *, fileplace//theFileA. This could be supported by the fact that the error message refers to just the trailing part of the file's name.

If this is the case, then use a "large" variable. You say 90 characters is as long as you need, so:

character(len=90) :: fileplace    ! Adjust length as desired
...
read(*,*) fileplace
...
open (newunit=iin, file=TRIM(fileplace)//theFileA, status='old')
...

Ensure you append the file's name to the trimmed directory name to avoid having spaces between the two parts.

[As a side note, you appear to not need theFileA and theFileB; just use the latter, considering that trailing blanks are ignored. And you may well want to force a trailing '/' on fileplace.]



来源:https://stackoverflow.com/questions/22000443/fortran-looping-over-file-names-with-common-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!