1 io modeling fortran numerical
希望有人可以帮助我解决这个问题。这将不胜感激。
背景。我正在为我们的研究小组扩展一段旧代码,该代码可以进行一些传热、热对流等类型的数值建模。我想做的是读取温度输入文件,以便我可以随着模型的进展及时调整模型的温度。虽然这些信息基本上无关紧要。在尝试关闭我打开并正在读取的文件时,我不断遇到分段错误。我附上了下面的代码以及典型的温度输入文件的样子(但由于有数千个数据点而大大简化)。在消除分段错误和/或纠正代码以使其更加高效方面的任何帮助将不胜感激。
subroutine Read_Temp_Input(Temp_in)!(dt)!(filename)!,dt,Temp_out)
implicit none
character*80 :: filename
integer, parameter :: dp = selected_real_kind(15)
real(kind=dp), allocatable, dimension(:,:) :: Temp_in, Temp_out
integer :: i,j,ierror,n
real (kind=dp) :: in_time, in_temp, dt, inter_time, inter_temp, max_time
character*80 :: line
!Variable definitions
!in_time is the time given from the input file
!in_temp is the temp given from the input file
!inter_time is the interpolated time using dt, max_time, and linear interpolation
!inter_temp is the interpolated temp using dt, max_time, and linear interpolation
!max_time is the largest time value in the input file
!dt is the time step utilized in the simulation, provided by main routine
!read in the temperature input file
filename = "temps.txt"
Open(UNIT=1,FILE=filename,ACTION="Read")
!Determine the size of the necessary allocation
n = 0
do
Read(1,*,iostat=ierror) in_time, in_temp
if (ierror.ne.0) then
exit
else
print*, in_time, in_temp
n = n + 1
endif
enddo
!Allocate the Temp_in array to a n x 2 array.
allocate(Temp_in(n,2))
close(unit=1)
Open(UNIT=1,FILE=filename,ACTION="Read")
n = 0
do
Read(1,*,iostat=ierror) in_time, in_temp
if (n.ne.0) then
if (ierror.ne.0) then
exit
else
Temp_in(n-1,0) = in_time
Temp_in(n-1,1) = in_temp
endif
endif
n = n + 1
enddo
dt = 0.5_dp
print*, 'is the fault before here?'
close(1)
print*, 'is the fault here?'
end subroutine
Run Code Online (Sandbox Code Playgroud)
温度文件
Time Temp
1 300
2 400
3 500
5 600
Run Code Online (Sandbox Code Playgroud)
附件也是我得到的输出。我会及时删除随机打印语句,只是使用它们来测试我的代码哪里出了问题。
感谢您的帮助,非常感谢。
Fortran 数组默认是从 1 开始的,Temp_in在您的示例中也是如此。所以这些行
Temp_in(n-1,0) = in_time
Temp_in(n-1,1) = in_temp
Run Code Online (Sandbox Code Playgroud)
会写出界(对于n=1,两者都是出界,第一个总是出界)。
您可以使用该--check=bounds标志让编译器为您检查这一点,如果您尝试以这种方式访问数组,它将抛出运行时错误。
所以要么分配Temp_in为
allocate(Temp_in(0:n-1,0:1))
Run Code Online (Sandbox Code Playgroud)
或使用基于 1 的索引进行写入作为解决方案。
更新
此外,在确定条目数时,读取示例文件的第一行将temps.txt失败,因为它尝试读取两行real,但却找到了其他内容。因此,您需要在打开文件后进行虚拟读取以在第一行中读取(或使用与第二个循环中相同的附加检查)
Open(UNIT=1,FILE=filename,ACTION="Read")
! read in the first line and throw it away
read(1,*)
! go on
Run Code Online (Sandbox Code Playgroud)