filename
(the dummy argument) is only one character long. Anything might happen if you provide a longer one (usually it is capped, though).
This does not result in an error as you did not specify the status
of the file, or even checked whether the operation was successful (In fact, you just created a new file d
).
You can avoid this by using an assumed length string:
function count_lines(filename) result(nlines)
character(len=*) :: filename
! ...
open(10,file=filename, iostat=io, status='old')
if (io/=0) stop 'Cannot open file! '
function count_lines(filename) result(nlines)
implicit none
character(len=*) :: filename
integer :: nlines
integer :: io
open(10,file=filename, iostat=io, status='old')
if (io/=0) stop 'Cannot open file! '
nlines = 0
do
read(10,*,iostat=io)
if (io/=0) exit
nlines = nlines + 1
end do
close(10)
end function count_lines
[Increment after the check to ensure a correct line count.]
For the second part of your question:
Positive (non-zero) error-codes correspond to any error other than IOSTAT_END
(end-of-file) or IOSTAT_EOR
(end-of-record). After reading in the (new) file in the first round of the loop (io==IOSTAT_END
, I checked with my compiler), you are trying to read beyond the end... This results in a positive error. Since the increment occurs before you exit the loop, the final value is 2
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…