我一直在编写一个程序,它使用OPEN语句从文件读取一个整数值,并在控制台上打印该值。
在编译期间,似乎没问题,没有问题,但是当我运行程序时,我遇到了分段错误。
我已经查看了代码,到目前为止我还没有违反任何规则。有人可以给我一个关于这个问题的想法吗?
错误:
代码:
program project5_03
implicit none
integer :: n = 0
open ( unit = 21, file = 'trial.txt', status = 'old')
read (21,*) n
print '(1x,a,i4)', "this is the value of n", n
stop
end program
txt文件的内容只是第一行的数字“1234”。
答案 0 :(得分:0)
我要做的是使用错误状态和-message变量,如下所示:
program project5_03
implicit none
integer :: n
integer :: ios
character(len=200) :: iomsg
open (unit=21, file='trial.txt', status='old', iostat=ios, iomsg=iomsg)
call check(ios, iomsg, "OPEN")
read (21,*, iostat=ios, iomsg=iomsg) n
call check(ios, iomsg, "READ n")
write(*,'(1x,a,i4)', iostat=ios, iomsg=iomsg), "this is the value of n", n
call check(ios, iomsg, "WRITE to STDOUT")
stop
contains
subroutine check(ios, iomsg, op)
implicit none
integer, intent(in) :: ios
character(len=*), intent(in) :: iomsg, op
if (ios == 0) return
print*, "Encountered Error ", ios, " during ", op
print*, iomsg
stop
end subroutine check
end program
也许这会帮助您找到错误。
还有一个事实是您使用integer :: n = 0
- 这不应该是主程序的问题,但在子程序中这意味着SAVE
属性。