2017-07-27 50 views
0

我提前道歉,因为已经有这类问题的帖子,但我是Fortran新手,我不理解他们。 我想使输入文件名的子程序。用任何随机名打开文件的子程序

我已经写了下面的代码,但它不能按需要工作。

PROGRAM reading 
implicit none 
integer::dati,n 
character::namefile 

namefile=file.txt 

call read(n,dati,namefile) 
print*,'Number of data:',dati 

END PROGRAM reading 


SUBROUTINE read(n,num,namefile) 
character::namefile 
Integer::n 
integer, intent(out)::num 
open(40,file='namefile') 
n=0 
do    
n=n+1 
read(40,*,end=999) 
enddo 

999 continue 
num=n-1 
END SUBROUTINE read 

感谢

+0

我知道有些东西没有道理。 –

回答

2

有一个名为READ的内部函数,而您SUBROUTINE被称为READ,它也包含名为READ的内部函数。

如果您的子程序使用了像SUBROUTINE My_Reader这样的名称,那么它与内部READ不同。

这应该工作,或接近它。

PROGRAM reading 
implicit none 
integer   :: dati, n 
character(LEN=40) :: FileName 
LOGICAL   :: An_Error 

FileName = 'file.txt' 

call My_Reader(FileName, dati, An_Error) 
IF(An_Error) THEN 
    WRITE(*,*)'I had an error finding file="',FileName(1:LEN_TRIM(FileName)),'"' 
ELSE 
    print*,'Number of data:',dati 
ENDIF 

END PROGRAM reading 


!===================== 
SUBROUTINE My_Reader(FileName, Num, An_Error) 
character, LEN=*, INTENT(IN ) :: FileName 
integer ,  INTENT( OUT) :: num 
LOGICAL ,  INTENT( OUT) :: An_Error 

character(LEN=256)    :: TextLine 
Integer       :: My_LUN 
LOGICAL       :: It_Exists 

INQUIRE(File=FileName, EXIST=It_Exists) 
IF(It_Exists) THEN 
    An_Error = .FALSE. 
ELSE 
    An_Error = .TRUE. 
    RETURN 
ENDIF 

OPEN(NEWUNIT=My_LUN, FILE=FileName) 

num = 0 
DO WHILE (.TRUE.) 
    read(My_LUN,900,end=999) TextLine 
900 FORMAT(A) 
    num = num + 1 
enddo 

999 continue 
CLOSE(My_LUN) 

REURN 
END SUBROUTINE My_Reader 
+0

没有(标准)内部程序叫'read'。 – francescalus

+0

没错,这是一个声明...... – Holmz

+1

因为在名为'read'和'read'的子程序之间没有混淆,所以我不明白你最初的意见。 – francescalus

1

原始代码混淆使用'分隔的名字。有两个问题:

1)在以下行中,文件的名称未用引号括起来('"将在Fortran中执行,但对必须匹配)。因此,改变

namefile=file.txt 

namefile='file.txt' 

2)相反,在这一行

open(40,file='namefile') 

变量名是用引号括起来,不应该。将其更改为

open(40,file=namefile) 

“namefile”指定该文件的名称是namefile,而namefile指定的文件名存储在名为namefile变量。