Uts_137
Uts_137

Reputation: 21

Problem with writing .dat files using Fortran

I am reading a .txt file and writing to a .dat file for use in GrADS. The .txt file contains 1D data, and my program reads all 123 lines correctly as I checked by printing on screen. However, the result .dat file only contains the very first line of data, the rest are all zeros. How can I fix this? Did I set the dimensions in write incorrectly?

Here is my code:

program convert
integer,parameter::nlon=1,nlat=1,nz=123
real,dimension(nlat,nlon,nz)::pr
integer::ilon,ilat,iz

open(2,file='2020082100_1.txt',form='formatted',status='old')

INQUIRE(IOLENGTH=LREC) pr

open(3,file='2020082100_1.dat',form='unformatted', &
access='direct',recl=LREC)

do iz=1,nz
  do ilat=nlat,1,-1
    read(2,*) (pr(ilat,ilon,iz),ilon=1,1)
  end do
end do

IREC=1
do iz=1,nz
  write(3,rec=irec) ((pr(ilat,ilon,iz),ilon=1,nlon),ilat=1,nlat)
  IREC=IREC+1
end do

close(2)
close(3)

end program convert

For example, the first few lines of the .txt file are:

30.7
29.4
25.9
24.2
24.4
...

However, the .dat file contains this:

30.7
0
0
0
0
...

Upvotes: 1

Views: 223

Answers (1)

Uts_137
Uts_137

Reputation: 21

So after tinkering with the code for a few hours, I figured out how to fix it myself.

Since all the data is writing on the wrong axis, I simply need to change a single line of code:

from this:write(3,rec=irec) ((pr(ilat,ilon,iz),ilon=1,nlon),ilat=1,nlat)

to this: write(3,rec=iz) ((pr(iz,ilon,ilat),ilon=1,nlon),ilat=1,nlat).

By changing this it completely worked. I did actually set the dimensions in write incorrectly.

Upvotes: 1

Related Questions