ncvar_attr.c 1.49 KB
/*
 * get parameter info from nc file
 * args : ncfile varId infoId
 * infoId :
 * UNITS
 * FILLVALUE
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netcdf.h>
 
void check(int stat) 
{
	if (stat != NC_NOERR) 
	{
		printf("error: %s\n", nc_strerror(stat));
		exit(1);
	}
} 
 
main(int argc, char **argv)
{
	int ncID, varID;
	size_t i, k;
//	char varname[NC_MAX_NAME];
	int stat = 0;
	nc_type xtype;
	char name_in[NC_MAX_NAME];
	float number_attr;
	int nattsp;

	if (argc <= 3) {
		printf("Incorrect number of arguments\n"); 
		exit(1);
	}
	
	check(nc_open(argv[1],NC_WRITE|NC_SHARE,&ncID));

	check(nc_inq_varid(ncID, argv[2], &varID));
	check(nc_inq_varnatts(ncID, varID, &nattsp));
	// fprintf(stdout, "%d\n", nattsp);
	
	for (i = 0; i < nattsp; i++) {
		check(nc_inq_attname(ncID, varID, i, name_in));
		 
		if (strcasecmp(name_in, argv[3]) == 0) { 

			check(nc_inq_atttype(ncID, varID, name_in, &xtype));
			
			if (xtype == NC_CHAR) {
				size_t attlen = 0;
				check(nc_inq_attlen(ncID, varID, name_in, &attlen));
				unsigned char *string_attr = (unsigned char *)malloc(attlen * sizeof(char*) + 1);	
				 
				check(nc_get_att(ncID, varID, name_in, string_attr));
				strcpy(&string_attr[attlen],"\0"); 
				fprintf(stdout, "%s\n",  string_attr);	
				free(string_attr);
			}
			else {
				check(nc_get_att(ncID, varID, name_in, &number_attr));
				fprintf(stdout, "%e\n",  number_attr);	
			}
			
			exit(0);
		}
	}
	
	stat = nc_close(ncID);
	fprintf(stdout, "undefined\n");
	exit(0);
}