Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28494 Discussions

File Unit Numbering in Main Program and Subroutines

gryvon
Beginner
553 Views

I'm sorry for asking trivial questions, but please look at the simple code below. It consists of two modules both of which contain reading from ASCII files.

program bpro
implicit none
character*6, parameter :: FNameSt = 'bp.txt'
integer*8, parameter :: FUnitNo = 15
integer*8 :: i
open(unit = FUnitNo, file = FNameSt)
read(FUnitNo, *) i
write(*, *) 'Number in 1st line of bp.txt = ', i
call bsub()
read(FUnitNo, *) i
write(*, *) 'Number in 2nd line of bp.txt = ', i
close(unit = FUnitNo)
stop
end program bpro
c

subroutine bsub
implicit none
character*6, parameter :: FNameSt = 'bs.txt'
integer*8, parameter :: FUnitNo = 15
integer*8 :: i
open(unit = FUnitNo, file = FNameSt)
read(FUnitNo, *) i
write(*, *) 'Number in 1st line of bs.txt = ', i
close(unit = FUnitNo)
return
end subroutine bsub

The file "bp.txt" contains 2 (two) lines:

11
12

The file "bs.txt" contains1 (one) line:

21

If I use _same_ unit numbers in the program and in the subroutine, I get thefollowing screen output:

Number in 1st line of bp.txt = 11
Number in 1st line of bs.txt = 21
forrtl: severe (29): file not found, unit 15, file D: est estDebugfort.15
Image PC Routine Line Source
q.exe 004951D2 Unknown Unknown Unknown
q.exe 0049246C Unknown Unknown Unknown
q.exe 0040C7DE Unknown Unknown Unknown
q.exe 0040C3FB Unknown Unknown Unknown
q.exe& nbsp; 00403E1B Unknown Unknown Unknown
q.exe 0040126C _MAIN__ 10 bpro.f
q.exe 0049B920 Unknown Unknown Unknown
q.exe 0043DBF3 Unknown Unknown Unknown
q.exe 0043D9BD Unknown Unknown Unknown
kernel32.dll 7C816FD7 Unknown Unknown Unknown

However, if I use _different_ unit numbers in the program and in the subroutine, I get the correct screen output:

Number in 1st line of bp.txt = 11
Number in 1st line of bs.txt = 21
Number in 2nd line of bp.txt = 12

Please let me know your opinion on this matter. I thought the unit numbers could be same in independent program modules... Like using similar local variable names with no confusion. Am I wrong?

0 Kudos
1 Reply
Jugoslav_Dujic
Valued Contributor II
553 Views
Your code amounts to

open(unit = FUnitNo, file = FNameSt)
read(FUnitNo, *) i
open(unit = FUnitNo, file = FNameSt)
read(FUnitNo, *) i
close(unit = FUnitNo)
read(FUnitNo, *) i
close(unit = FUnitNo)

If you use same unit numbers, the second OPEN implicitly closes the previously open unit, and first CLOSE closes the unit forever. The last READ will fail, seeking to read from default file title "fort.15". Unit numbers are global (perhaps the only global thing in Fortran) -- it perhaps wasn't the best design decision, but it's part of the history.
0 Kudos
Reply