[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[netCDF #EQZ-362025]: bug in nc_rename_var for NETCDF3 formatted files



Hi Jeff,

> This test program triggers the bug:
> 
> #include <stdlib.h>
> #include <stdio.h>
> #include "netcdf.h"
> 
> #define ERRCODE 2
> #define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}
> 
> int
> main()
> {
> int ncid, varid, dimid, retval;
> 
> if ((retval = nc_create("test.nc", NC_64BIT_OFFSET, &ncid)))
> ERR(retval);
> if ((retval = nc_def_dim(ncid, "x", 1, &dimid))) ERR(retval);
> if ((retval = nc_def_var(ncid, "SurfPres_A", NC_FLOAT, 1, &dimid,
> &varid))) ERR(retval);
> nc_close(ncid);
> if ((retval = nc_open("test.nc", NC_WRITE, &ncid))) ERR(retval);
> if ((retval = nc_inq_varid(ncid, "SurfPres_A", &varid))) ERR(retval);
> /* this fails with "Operation not allowed in data mode" ?? */
> if ((retval = nc_rename_var(ncid, varid, "surface_air_pressure")))
> ERR(retval);
> /* this works */
> /*if ((retval = nc_rename_var(ncid, varid, "sfc_air_pr")))
> ERR(retval);*/
> nc_close(ncid);
> }
> 
> jeff-whitakers-imac:netcdf4-python jsw$ ./a.out
> Error: NetCDF: Operation not allowed in data mode
> 
> It the file format is changed to NETCDF4 or NETCDF4_CLASSIC, the error
> does not occur.
> 
> The error also goes away if the variable name is shortened.

This is actually not a bug, but the documented behavior of netCDF-3,
illustrating one of the limitations of the netCDF-3 format that
motivated development of netCDF-4.  But there is a workaround if you
use the nc__endef() function before calling nc_close() to add some
extra space to the file header for renaming things with longer names.

First, note this documented restriction on calling nc_rename() when in
data mode:

  The function nc_rename_var changes the name of a netCDF variable in
  an open netCDF dataset. If the new name is longer than the old name,
  the netCDF dataset must be in define mode.
  http://www.unidata.ucar.edu/netcdf/docs/netcdf-c/nc_005frename_005fvar.html

Here is an explanation of why the fixed header space at the beginning
of a netCDF-3 file presents a problem when extra space is needed for a
longer name:

  
http://www.unidata.ucar.edu/netcdf/docs/netcdf/Parts-of-a-NetCDF-Classic-File.html

Finally here is the documentation for the nc__endef() function (note
it has two underscores) that provides a workaround:

  http://www.unidata.ucar.edu/netcdf/docs/netcdf-c/nc_005f_005fenddef.html

One of the benefits of the netCDF-4 format (including the classic
model format that uses only the netCDF-3 API and data model) is that
the file schema may be changed without incurring the cost of copying
data.  This includes renaming things to longer sizes.

--Russ

Russ Rew                                         UCAR Unidata Program
address@hidden                     http://www.unidata.ucar.edu



Ticket Details
===================
Ticket ID: EQZ-362025
Department: Support netCDF
Priority: Normal
Status: Closed