Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example to read a field from GrADS file and write to NetCDF file
program grads_to_netcdf
! Example program that reads a GrADS file and writes the field to NetCDF file.
! With GNU Fortran, compile as:
! gfortran -fconvert=big-endian grads_to_netcdf.f90 -I$NETCDF/include -L$NETCDF/lib -lnetcdf -lnetcdff
! With Intel Fortran, compile as:
! ifort -convert big_endian -assume byterecl grads_to_netcdf.f90 -I$NETCDF/include -L$NETCDF/lib -lnetcdf -lnetcdff
! use portable 4-byte reals
use iso_fortran_env, only: real32
use netcdf
implicit none
character(len=*), parameter :: filename = 'taucw.grd' ! file to read
integer, parameter :: im = 2880, jm = 1440, nm = 60 ! grid dimensions
integer :: fileunit
integer :: record_length
integer :: ncid, xdimid, ydimid, tdimid, varid, stat
real(kind=real32) :: field(im,jm,nm) ! 3-d array to store data
record_length = storage_size(field) / 8 * size(field)
open(newunit=fileunit, file=filename, access='direct', recl=record_length)
read(unit=fileunit, rec=1) field
stat = nf90_create('', nf90_clobber, ncid)
! write(*,*) nf90_strerror(stat) ! uncomment to debug NetCDF calls; add to other calls if needed
stat = nf90_def_dim(ncid, 'x', im, xdimid)
stat = nf90_def_dim(ncid, 'y', jm, ydimid)
stat = nf90_def_dim(ncid, 'Time', nm, tdimid)
stat = nf90_def_var(ncid, 'taucw', nf90_float, [xdimid, ydimid, tdimid], varid)
stat = nf90_enddef(ncid)
stat = nf90_put_var(ncid, varid, field)
stat = nf90_close(ncid)
end program grads_to_netcdf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment