Search code examples
fortrannetcdfnetcdf4

Checking if a NETCDF file already exists


What's the best way to check whether a given netCDF file exists in Fortran90? I have a Fortran program which simulates several systems and stores the data in a NETCDF file, and I'd like to be able to set it up so that I can run the code with already-existing netCDF files and just append the extra data.

It seems to work with the following:

status = nf90_open(filePath, NF90_WRITE, netcdfID)
if (status /= nf90_noerr) then
    new_status = nf90_create(filePath, NF90_NETCDF4, netcdfID)
    ! setup
else
    ! check file has correct dimensions etc
end if

But I'd like to be able to be specific about the error, but the documentation isn't very specific about what the error code is when the file already exists.

I've also considered checking the status of the nf90_create(...) call, but I don't know how to specify cmode=NF90_NETCDF4 and cmode=NF90_NOCLOBBER at the same time.


Solution

  • To be honest, when I use NetCDF with Fortran and need to look at the documentation, I look at the C-documentation at https://www.unidata.ucar.edu/software/netcdf/docs/modules.html and 'translate' it to the Fortran API (for example replacing the nc_ with nf90_) because the C documentation is far more current than the Fortran one.

    There seem to be these possible status results:

    • NF90_NOERR No error.
    • NF90_EPERM Attempting to create a netCDF file in a directory where you do not have permission to open files.
    • NF90_ENFILE Too many files open
    • NF90_ENOMEM Out of memory.
    • NF90_EHDFERR HDF5 error. (NetCDF-4 files only.)
    • NF90_EDIMMETA Error in netCDF-4 dimension metadata. (NetCDF-4 files only.)

    None of these suggest that you were opening a file that doesn't exist. Maybe try it out?

    But if you only want to know whether the file already exists, why not use Fortran's INQUIRE statement?

    logical :: fileExists
    ...
    inquire(file=filePath, exist=fileExists)
    if (fileExists) then
        call nf90_open(
    else
        call nf90_create(
    end if