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

Re: 980619: attribute trouble



>To: address@hidden
>From: Nan Rosenbloom <address@hidden>
>Subject: attribute trouble
>Organization: .
>Keywords: 199806191941.NAA03654

Hi Nan,

> I am a frequent user of netCDF files, reading and writing netcdf using C
> code.
> 
> I have a recurring problem assigning (or possibly reading) a specific
> attribute (note, I am not following general protocol for attribute
> labels).  Sorry to trouble you with such a trivial problem, but if you
> can spot my error, I would be most appreciative.  I have been
> replicating the error for months :< and now am ready to send the files
> out for public consumption (how embarrassing).
> 
> I assign 2 (of many) attribute using these lines of code:
> 
>    #define LSCALED 3
>    #define LSOURCE 20
> 
> 
>    ncattput(ncid, id, "scaled", NC_CHAR, LSCALED, "1.0");
>    ncattput(ncid, id, "source", NC_CHAR, LSOURCE,
> "NCAR+OregonStateUniv");
> 
> When I read the netcdf file, it looks like this:
>   netcdf txdyT1 {
>   dimensions:
>         day = 36159 ;
>         grid = UNLIMITED ; // (3261 currently)
>   variables:
>         float tx(grid, day) ;
>                 tx:longname = "maximum temperature" ;
>                 tx:scaled = "1.0" ;
>                 tx:source = "NCAR+OregonStateUniv" ;
>                 tx:version = "v1" ;
>                 tx:created = "1/1/98" ;
>                 tx:period_of_record = "Jan 1895 - Dec 1993" ;
> 
> etc.  But when I read the netcdf file using C code lines:
> 
> /* --- retrieve variable scaling factor --- */
>         ncattinq(ncid,varid,"scaled",&vr_type, &vr_len);
>         vr_val = malloc(vr_len*nctypelen(vr_type));
>         ncattget(ncid,varid,"scaled",vr_val);
>         fprintf(fp_out,"scaling factor = %s \n", vr_val);
> 
> I get funny characters for the "scaled" string:
> 
>           file = txdyT1.nc
>  Variable name = tx
>          units = degrees C 
> scaling factor = 1.0È   <<<<<--------------
> 
> This happens in EVERY file I write, even if I assign different string
> lengths to "scaled" when I write it.  It never happens to any of the
> other attributes...???
> 
> Any clues what I am doing wrong?  thanks much!

Yes, you are making the (reasonable) assumption that netCDF returns
character array attributes in the form of C strings, properly terminated
with a null '\0' character.  However netCDF files are language-neutral,
so Fortran programs can read the files too.  There is only a null
character terminating a string attribute if you put it there when you
wrote it, and specified the attribute length (number of characters) to
include the extra null character.  So you need to have LSCALED defined
as 4 and LSOURCE defined as 21 to get the effect you expect.

--Russ