fortran如何读取nc文件
如果没有fortran-c库需要先安装fortran-c,再安装fortran-netcdf库,参考网址:
若服务器上Fortran-netcdf库已安装好:
1: 向管理员要netcdf库的"r-x"权限,我们服务器的安装路径为 /home/hjh/netcdf
2: 环境配置:
$vi ~/.bashrc
# NETCDF
export PATH=/home/hjh/netcdf/bin:$PATH
export LD_LIBRARY_PATH=/home/hjh/netcdf/lib:$LD_LIBRARY_PATH
$source ~/.bashrc
如果没配置会在运行.exe时报错:error while loading shared libraries: libnetcdff.so.7: cannot open shared object file: No such file or directory
3: 在test.f90文件中:
program main
use netCDF
4: 编译.f文件时链接netcdf库:
$h5fc test.f90 -I/home/hjh/netcdf/include -L/home/hjh/netcdf/lib -lnetcdff -lnetcdf -o test.exe
----------------------------------------------------------------
program示例:
用ncdump查看变量名称和DIM名称:
$ncdump -h /data04/1/xxy/thompson/thompson_data/3h/mpas_out.2020-06-12_21.00.00/qi.nc
变量名qc,维度"nCells"长65536002,维度"nVertLevels"长56,test.f90代码:
! include '/home/hjh/netcdf/include/netcdf.inc'
program main
use netCDF
implicit none
integer:: status, fidA, dimID ! 通用
integer:: qc_ID !变量ID
integer:: nloc,nh
real , dimension(:,:) , allocatable :: qc
real , dimension(:) , allocatable :: lat, lon
CHARACTER(LEN=100) :: file_in
file_in = '/data04/1/xxy/thompson/thompson_data/3h/mpas_out.2020-06-12_21.00.00/qc.nc'
!----------------------------------------------------------------
! 打开文件 :
call erreur(NF90_OPEN(TRIM(file_in),0,fidA),.TRUE.,"read_A")
!- read ID of dimensions of interest and save them in-----------------
! 获取长度维变量ID
call erreur(NF90_INQ_DIMID(fidA,"nCells",dimID),.TRUE.,"inq_dimID")
! 获取长度维:
call erreur(NF90_INQUIRE_DIMENSION(fidA,dimID,len=nloc),.TRUE.,"inq_dim")
! 获取高度维变量ID:
call erreur(NF90_INQ_DIMID(fidA,"nVertLevels",dimID),.TRUE.,"inq_dimID")
! 获取高度维:
call erreur(NF90_INQUIRE_DIMENSION(fidA,dimID,len=nh),.TRUE.,"inq_dim")
print*,nloc,nh
!- Allocation of arrays :
ALLOCATE( qc(nh,nloc) )
!- 获取变量ID :
status = NF90_INQ_VARID(fidA,"qc",qc_ID)
call erreur(status,.TRUE.,"inq_qc_ID")
!- 获取变量值 :
call erreur(NF90_GET_VAR(fidA,qc_ID,qc),.TRUE.,"getvar_qc")
!- close netcdf file :
call erreur(NF90_CLOSE(fidA),.TRUE.,"close_A")
end
SUBROUTINE erreur(iret, lstop, chaine)
! used to provide clear error messages :
USE netcdf
INTEGER, INTENT(in) :: iret
LOGICAL, INTENT(in) :: lstop
CHARACTER(LEN=*), INTENT(in) :: chaine
!
CHARACTER(LEN=80) :: message
!
IF ( iret .NE. 0 ) THEN
WRITE(*,*) 'ROUTINE: ', TRIM(chaine)
WRITE(*,*) 'ERROR: ', iret
message=NF90_STRERROR(iret)
WRITE(*,*) 'WHICH MEANS:',TRIM(message)
IF ( lstop ) STOP
ENDIF
!
END SUBROUTINE erreur
若非整个变量读取,可以给NF90_GET_VAR设定参数:参考 6.11
NF90_GET_VAR(fidA,dataID,zgrid0,start=(/1,3/),count=(/57,10/),stride=(/1,20/)