iterator.c

iterator.c How to use an iterator on latitude, longitude, values.

00001 
00010 /*
00011  * C Implementation: iterator
00012  *
00013  * Description: how to use an iterator on lat/lon/values.
00014  *
00015  *
00016  * Author: Enrico Fucile
00017  *
00018  *
00019  */
00020 
00021 #include <stdio.h>
00022 #include <stdlib.h>
00023 #include <string.h>
00024 
00025 #include "grib_api.h"  
00026 
00027 void usage(char* prog) {
00028   printf("Usage: %s grib_file\n",prog);
00029   exit(1);
00030 }
00031 
00032 int main(int argc, char** argv) {
00033   FILE* in = NULL;
00034   int err = 0;
00035   double lat,lon,value,missingValue=0;
00036   int n=0;
00037   char* filename = NULL;
00038 
00039   /* Message handle. Required in all the grib_api calls acting on a message.*/
00040   grib_handle *h = NULL;   
00041   /* Iterator on lat/lon/values.*/
00042   grib_iterator* iter=NULL;  
00043   
00044   if (argc != 2) usage(argv[0]);
00045 
00046   filename=strdup(argv[1]);
00047 
00048   in = fopen(filename,"r");
00049   if(!in) {
00050     printf("ERROR: unable to open file %s\n",filename);
00051     return 1;
00052   }
00053 
00054   /* Loop on all the messages in a file.*/
00055   while ((h = grib_handle_new_from_file(0,in,&err)) != NULL ) { 
00056         /* Check of errors after reading a message. */
00057     if (err != GRIB_SUCCESS) GRIB_CHECK(err,0);                       
00058 
00059         /* Get the double representing the missing value in the field. */
00060         GRIB_CHECK(grib_get_double(h,"missingValue",&missingValue),0);  
00061 
00062         /* A new iterator on lat/lon/values is created from the message handle h. */
00063         iter=grib_iterator_new(h,0,&err);                                     
00064     if (err != GRIB_SUCCESS) GRIB_CHECK(err,0);                       
00065 
00066     n = 0;
00067         /* Loop on all the lat/lon/values. */
00068     while(grib_iterator_next(iter,&lat,&lon,&value)) {   
00069           /* You can now print lat and lon,  */
00070       printf("- %d - lat=%f lon=%f value=",n,lat,lon);   
00071           /* decide what to print if a missing value is found. */
00072       if (value == missingValue ) printf("missing\n");   
00073           /* and print the value if is not missing. */
00074           else printf("%f\n",value);
00075       n++;
00076     }
00077 
00078         /* At the end the iterator is deleted to free memory. */
00079     grib_iterator_delete(iter);               
00080 
00081     /* At the end the grib_handle is deleted to free memory. */
00082     grib_handle_delete(h);            
00083   }
00084 
00085 
00086   fclose(in);
00087 
00088   return 0;
00089 }

Generated on Tue Sep 22 15:18:21 2009 for grib_api by  doxygen 1.5.3