我正在运行一个模型并将模型输出写入二进制文件(GrADS *gra 文件),例如:
integer,parameter :: nvar =3 ,& !number of variables to be written to file
nx=10,ny=10,& !number of girdboxes in lat & long
nt = 5
integer :: it, & ! loop counter
irec ! Record number
real :: var1(nx,ny), var2(nx,ny),var3(nx,ny)
OPEN(30,file='Outfile.gra',action='write',form='unformatted',access='direct',&
recl=4*nVar*nx*ny,status='replace')
!loop over timesteps
it = 1, nt
irec = irec + 1
WRITE(1,rec=irec) Var1(:,:),Var2(:,:),Var3(:,:)
enddo
Run Code Online (Sandbox Code Playgroud)
该文件可以在 GrADS 中读取,*ctl 文件如下所示
dset /mypath/Outfile.gra
title MyTitle
options little_endian
xdef 10 linear 1 1
ydef 10 linear 1 1
zdef 1 linear 1.0 1.0
tdef 5 linear 00:00Z01jan2012 1hr
vars 3
var1
var2
var3
endvars
Run Code Online (Sandbox Code Playgroud)
我想做的是,从一个单独的程序中,将 1 个时间步长的 1 个变量的所有 x&y 写入文本文件。我尝试了多种方法,但没有任何效果。我最近的尝试是这样的:
integer,parameter :: &
t = 3, & !Timestep I want to write to file
field = 2, & !Variable I want to write to file
nvar =3 , & !number of variables to be written to file
nx=10,ny=10, & !number of girdboxes in lat & long
nt = 5 !number of timesteps
inte?er :: it,ix,iy,& ! loop counters
irec ! Record number
real :: val(nx,ny) ! Data to be written to file
open(1,file='NewFile.txt',status='replace')
open(2,file='Outfile.gra',action='read',form='unformatted',access='direct',&
recl=4*nVar*nx*ny,status='old')
irec = 0
do it = 1,nt
irec=irec + nvar*nx*ny
if(it == t) then
irec = irec + (field-1)*nx*ny
do ix = 1,nx
do iy = 1,ny
irec=irec+1
read(2,rec=irec) val(ix,iy)
enddo
enddo
write(1,*) val(:,:)
Run Code Online (Sandbox Code Playgroud)
这个特定的例子给了我以下错误
Fortran 运行时错误:不存在的记录号
但我尝试了其他变体,它们没有给我任何错误,但只是没有写出我试图写入文件的内容。有人能告诉我我做错了什么以及如何解决这个问题吗?谢谢你。
好的,让我再试一次。当您写入时,outfile.gra您似乎nt在块中向其写入记录
!loop over timesteps
it = 1, nt
irec = irec + 1
WRITE(1,rec=irec) Var1(:,:),Var2(:,:),Var3(:,:)
enddo
Run Code Online (Sandbox Code Playgroud)
我想这irec是0在代码中的某个地方初始化的。 nt设置为5如此,如果我的猜测是正确的,您的代码会将 5 条记录写入outfile.gra.
稍后,您在此块中读取相同的文件
irec = 0
do it = 1,nt
irec=irec + nvar*nx*ny
if(it == t) then
irec = irec + (field-1)*nx*ny
do ix = 1,nx
do iy = 1,ny
irec=irec+1
read(2,rec=irec) val(ix,iy)
enddo
enddo
Run Code Online (Sandbox Code Playgroud)
目前尚不清楚该if语句在哪里结束,但从您的问题来看,我猜它在循环结束后关闭nxand ny,如下所示:
irec = 0
do it = 1,nt
irec=irec + nvar*nx*ny
if(it == t) then
irec = irec + (field-1)*nx*ny
do ix = 1,nx
do iy = 1,ny
irec=irec+1
read(2,rec=irec) val(ix,iy)
enddo
enddo
end if
Run Code Online (Sandbox Code Playgroud)
同样,如果我的猜测是正确的,那么irec在第一次执行语句401时具有值read。
您似乎已经向其中写入了 5 条记录,outfile.gra并且正在尝试从中读取第 401 条记录。运行时报告您正在尝试读取不存在的记录是完全合理的。
| 归档时间: |
|
| 查看次数: |
6422 次 |
| 最近记录: |