Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Description

This example shows: how to use keys_iterator functions and the codes_bufr_keys_iterator structure to get all the available keys in a BUFR message.

Source code

Tabs Container
directionhorizontal


Tabs Page
titleFortran 90


Code Block
languagenone
titlebufr_keys_iterator.f90
linenumbersfalse
!
! (C) Copyright 2005-2018 ECMWF.
!
! This software is licensed under the terms of the Apache Licence Version 2.0
! which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
!
! In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
! virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
!
!
! FORTRAN 90 implementation: bufr_keys_iterator
!
!
! Description: howHow to use keys_iterator functions and the
!              codes_bufr_keys_iterator structure to get all the available
!              keys in a BUFR message.
!
!
program bufr_keys_iterator
   use eccodes
   implicit none
   integer            :: ifile
   integer            :: iret
   integer            :: ibufr
   integer            :: count = 0
   character(len=256) :: key
   integer            :: kiter

   integer call codes_open           :: subset = 1

   call codes_open_file(ifile, '../../data/bufr/syno_1.bufr', 'r')

   ! The first bufrBUFR message is loaded from file,
   ! ibufr is the bufrBUFR id to be used in subsequent calls
   call codes_bufr_new_from_file(ifile, ibufr, iret)

   do while (iret /= CODES_END_OF_FILE)

      ! Get and print some keys formfrom the BUFR header
      write (*, *) 'message: ', count

      ! We need to instruct ecCodes to expand all the descriptors
      ! i.e. unpack the data values
      call codes_set(ibufr, "unpack", 1); 

      ! Create BUFR keys iterator
      call codes_bufr_keys_iterator_new(ibufr, kiter, iret)

      if (iret .ne. 0) then
         write (*, *) 'ERROR: Unable to create BUFR keys iterator'
         call exit(1)
      end if

      ! Get first key
      call codes_bufr_keys_iterator_next(kiter, iret)

      ! Loop over keys
      do while (iret == CODES_SUCCESS)
         ! Print key name
         call codes_bufr_keys_iterator_get_name(kiter, key)
         if write(*,*)(key == '  ',trim(key)

subsetNumber') then
          ! Get next key
  write (*, *) '  Subset ', subset
  call codes_bufr_keys_iterator_next(kiter, iret)
    end do

   subset != Deletesubset key+ iterator1
        call codes_bufr_keys_iterator_delete(kiter)
 else
    ! Release the bufr message
    callwrite codes_release(ibufr)

    ! Load the next bufr message
(*, *) '  ', trim(key)
         end if

         ! Get next key
         call codes_bufr_newkeys_fromiterator_filenext(ifilekiter,ibufr, iret)

    count=count+1

  end do

  ! Close file
   ! Delete key iterator
      call codes_bufr_keys_closeiterator_filedelete(ifilekiter)

end program bufr_keys_iterator
Tabs Page
titlePython
Code Block
languagepython
titlebufr_keys_iterator.py
linenumbersfalse
# Copyright   ! Release the BUFR message
      call codes_release(ibufr)

      ! Load the next BUFR message
      call codes_bufr_new_from_file(ifile, ibufr, iret)

      count = count + 1

   end do

   ! Close file
   call codes_close_file(ifile)

end program bufr_keys_iterator 



Tabs Page
titlePython


Code Block
languagepython
titlebufr_keys_iterator.py
linenumbersfalse
# (C) Copyright 2005- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.

#
# Python implementation: bufr_keys_iterator
#
# Description: Example on how to use keys_iterator functions and the
#              codes_bufr_keys_iterator structure to get all the available
#              keys in a BUFR message.


import sys
import traceback

from eccodes import *

VERBOSE = 1  # verbose error reporting


def example(INPUT):
    # open bufr file
    f = open(INPUT, "rb")

    cnt = 0
    subset = 0

    # loop for the messages in the file
    while 1:
        # get handle for message
        bufr = codes_bufr_new_from_file(f)
        if bufr is None:
            break

        print("message: %s" % cnt)

 2005-2018 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.

#
# Python implementation: bufr_keys_iterator
#
# Description: Example on how to use keys_iterator functions and the
#       # we need  codes_bufr_keys_iterator structureto instruct ecCodes to getexpand all the available
descriptors
        # i.e. unpack the data values
      keys in a BUFR message.


from __future__ import print_function
import traceback
import sys

from eccodes import *

INPUT = '../../data/bufr/syno_1.bufr'
VERBOSE = 1  # verbose error reporting


def example():
 codes_set(bufr, "unpack", 1)

        # get BUFR key iterator
        iterid = codes_bufr_keys_iterator_new(bufr)

        # loop openover bufrthe filekeys
      f = open(INPUT, 'rb')
while codes_bufr_keys_iterator_next(iterid):
    cnt = 0

    # loop for# theprint messageskey inname
 the file
    while 1:
     keyname =  # get handle for message
codes_bufr_keys_iterator_get_name(iterid)
            if bufrkeyname == codes_bufr_new_from_file(f)
"subsetNumber":
           if bufr is None:
  subset += 1
        break

        print("message  Subset: %s%d" % cntsubset)

        # we need to instruct ecCodes to expand all the descriptors
      else:
   # i.e. unpack the data values
        codes_set(bufr, 'unpack', 1print("  %s" % keyname)

        # getdelete BUFRthe key iterator
        iterid = codes_bufr_keys_iterator_newdelete(bufriterid)

        #cnt loop over the keys
+= 1

        #  while codes_bufr_keys_iterator_next(iterid):delete handle
        codes_release(bufr)

    # printclose keythe namefile
    f.close()


def main():
    try:
      keyname = codes_bufr_keys_iterator_get_name(iterid example(sys.argv[1])
    except CodesInternalError as  err:
    print("   %s" % keyname)
if VERBOSE:
        # delete the key iterator traceback.print_exc(file=sys.stderr)
        codes_bufr_keys_iterator_delete(iterid)

else:
            cntsys.stderr.write(err.msg += 1"\n")

        return  # delete handle1


if __name__ == "__main__":
    sys.exit(main())    codes_release(bufr)

    # close the file
    f.close()


def main():
    try:
        example()
    except CodesInternalError as err:
        if VERBOSE:
            traceback.print_exc(file=sys.stderr)
        else:
            sys.stderr.write(err.msg + '\n')

        return 1


if __name__ == "__main__":
    sys.exit(main())



Tabs Page
titleC


Code Block
languagecpp
titlebufr_keys_iterator.c
linenumbersfalse
/*
 * (C) Copyright 2005- ECMWF.
 *
 * This software is licensed under the terms of the Apache Licence Version 2.0
 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
 * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
 */
/*
 * C Implementation: bufr_keys_iterator
 *
 * Description: how to use keys_iterator functions and the
 *              codes_bufr_keys_iterator structure to get all the available
 *              keys in a BUFR message.
 *
 */

#include "eccodes.h"

#define MAX_VAL_LEN 1024

static void usage(const char* prog)
{
    printf("usage: %s infile\n", prog);
    exit(1);
}

int main(int argc, char* argv[])
{
    char* filename = NULL;
    FILE* in       = NULL;

    /* message handle. Required in all the eccodes calls acting on a message.*/
    codes_handle* h = NULL;
    int err = 0, cnt = 0;
    int keyType = 0;
    int subsetNumber = 0;

    char value[MAX_VAL_LEN];
    size_t vlen = MAX_VAL_LEN;
    size_t klen = 0;

    if (argc != 2) usage(argv[0]);

    filename = argv[1];

    in = fopen(filename, "rb");
    if (!in) {
        fprintf(stderr, "Error: unable to open file %s\n", filename);
        return 1;
    }

    /* loop over the messages in the BUFR file */
    while ((h = codes_handle_new_from_file(NULL, in, PRODUCT_BUFR, &err)) != NULL || err != CODES_SUCCESS) {
        codes_bufr_keys_iterator* kiter = NULL;
        if (h == NULL) {
            fprintf(stderr, "Error: unable to create handle for message %d\n", cnt);
            cnt++;
            continue;
        }

        printf("message: %d\n", cnt);

        /* we need to instruct ecCodes to unpack the data values */
        CODES_CHECK(codes_set_long(h, "unpack", 1), 0);
Tabs Page
titleC
Code Block
languagecpp
titlebufr_keys_iterator.c
linenumbersfalse
/*
 * Copyright 2005-2018 ECMWF.
 *
 * This software is licensed under the terms of the Apache Licence Version 2.0
 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
 * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
 */

/*
 * C Implementation: bufr_keys_iterator
 *
 * Description: how to use keys_iterator functions and the
 *              codes_bufr_keys_iterator structure to get all the available
 *              keys in a BUFR message.
 *
 */

#include "eccodes.h"

#define MAX_VAL_LEN  1024

static void usage(const char* prog) {
    printf("usage: %s infile\n",prog);
    exit(1);
}

int main(int argc,char* argv[])
{
    char* filename = NULL;
    FILE* in = NULL;

    /* message handle. Required in all the eccodes calls acting on a message.*/
    codes_handle* h=NULL;
    int err=0, cnt=0;
    int keyType = 0;

    char value[MAX_VAL_LEN];
    size_t vlen=MAX_VAL_LEN;
    size_t klen=0;

    if (argc!=2) usage(argv[0]);

    filename=argv[1];

    in=fopen(filename,"r");
    if (!in) {
        printf("ERROR: unable to open file %s\n", filename);
        return 1;
    }

    /* loop over the messages in the BUFR file */
    while ((h = codes_handle_new_from_file(NULL,in,PRODUCT_BUFR,&err)) != NULL || err != CODES_SUCCESS)
    {
        codes_bufr_keys_iterator* kiter=NULL;
        if (h == NULL) {
        /* get BUFR key printf("Error: unable to create handle for message %d\n",cnt);iterator */
        kiter =   cnt++codes_bufr_keys_iterator_new(h, 0);
        if (!kiter) {
  continue;
        }

  fprintf(stderr, "Error: Unable to create BUFR printf("message: %dkeys iterator\n",cnt);

        /* we need to instruct ecCodes to unpack the data values */ exit(1);
        CODES_CHECK(codes_set_long(h,"unpack",1),0);}

        /* getloop BUFRover keythe iteratorkeys */
        while kiter=(codes_bufr_keys_iterator_new(h,0);
next(kiter)) {
            if (!kiter) {
  /* get key name */
          printf("ERROR: Unable tochar* createname BUFR= codes_bufr_keys iterator\n"_iterator_get_name(kiter);
            if exit(1);(strcmp(name, "subsetNumber") == 0) {
        }

        /* loop over the keys */
subsetNumber++;
            while(codes_bufr_keys_iterator_next(kiter))
    printf("\n  Subset  {
   %d:\n", subsetNumber);
         /* get key name */
   continue;
         char* name = codes_bufr_keys_iterator_get_name(kiter); }
            printf("  %s=", name);

            CODES_CHECK(codes_get_native_type(h, name, &keyType), 0);

            /* get key size to see if it is an array */
            CODES_CHECK(codes_get_size(h, name, &klen), 0);

            if (klen == 1)
            {
                /* not array */
                vlen = MAX_VAL_LEN;
                bzeromemset(value, 0, vlen);
                codes_get_string(h, name, value, &vlen);
                printf("%s\n", value);
            }
            else {
                /* for arrays */
                printf("(array of %lu)\n", (unsigned long)klen);
            }
        }

        /* delete key iterator */
        codes_bufr_keys_iterator_delete(kiter);

        /* delete handle */
        codes_handle_delete(h);

        cnt++;
    }

    fclose(in);
    return 0;
}