keys_iterator.c

keys_iterator.c How to get the names of all the keys defined in a message and how to iterate through them.

00001 
00010 /*
00011  * C Implementation: keys_iterator
00012  *
00013  * Description:
00014  * Example on how to use keys_iterator functions and the
00015  * grib_keys_iterator structure to get all the available
00016  * keys in a message.
00017  *
00018  * Author: Enrico Fucile
00019  *
00020  *
00021  */
00022 
00023 #include <assert.h>
00024 #include <stdlib.h>
00025 #include <stdio.h>
00026 #include <unistd.h>
00027 
00028 #include "grib_api.h"
00029 
00030 #define MAX_KEY_LEN  255
00031 #define MAX_VAL_LEN  1024
00032 
00033 static void usage(char* progname);
00034 
00035 int main(int argc, char *argv[])
00036 {
00037   /* To skip read only and not coded keys
00038      unsigned long key_iterator_filter_flags=GRIB_KEYS_ITERATOR_SKIP_READ_ONLY ||
00039      GRIB_KEYS_ITERATOR_SKIP_COMPUTED;
00040   */
00041   unsigned long key_iterator_filter_flags=GRIB_KEYS_ITERATOR_ALL_KEYS;
00042 
00043   /* valid name_spaces are ls and mars */
00044   char* name_space="ls";
00045 
00046   /* name_space=NULL to get all the keys */
00047   /* char* name_space=0; */
00048 
00049   FILE* f;
00050   grib_handle* h=NULL;
00051   grib_keys_iterator* kiter=NULL;
00052   int err=0;
00053   int grib_count=0;
00054 
00055   char value[MAX_VAL_LEN];
00056   size_t vlen=MAX_VAL_LEN;
00057 
00058   if (argc != 2) usage(argv[0]);
00059 
00060   f = fopen(argv[1],"r");
00061   if(!f) {
00062     perror(argv[1]);
00063     exit(1);
00064   }
00065 
00066   while((h = grib_handle_new_from_file(0,f,&err)) != NULL) {
00067 
00068     grib_count++;
00069     printf("-- GRIB N. %d --\n",grib_count);
00070     if(!h) {
00071       printf("ERROR: Unable to create grib handle\n");
00072       exit(1);
00073     }
00074 
00075     kiter=grib_keys_iterator_new(h,key_iterator_filter_flags,name_space);
00076     if (!kiter) {
00077       printf("ERROR: Unable to create keys iterator\n");
00078       exit(1);
00079     }
00080 
00081     while(grib_keys_iterator_next(kiter))
00082     {
00083       const char* name = grib_keys_iterator_get_name(kiter);
00084       vlen=MAX_VAL_LEN;
00085       GRIB_CHECK(grib_get_string(h,name,value,&vlen),name);
00086       printf("%s = %s\n",name,value);
00087     }
00088 
00089     grib_keys_iterator_delete(kiter);
00090 
00091   }
00092 
00093   return 0;
00094 
00095 }
00096 
00097 static void usage(char* progname) {
00098   printf("\nUsage: %s grib_file\n",progname);
00099   exit(1);
00100 }
00101 

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