NCEPLIBS-g2c  1.8.0
seekgb.c
Go to the documentation of this file.
1 
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include "grib2_int.h"
16 
45 void
46 seekgb(FILE *lugb, g2int iseek, g2int mseek, g2int *lskip, g2int *lgrib)
47 {
48  g2int k, k4, ipos, nread, lim, start, vers, lengrib;
49  int end;
50  unsigned char *cbuf;
51 
52 
53  LOG((3, "seekgb iseek %ld mseek %ld", iseek, mseek));
54 
55  *lgrib = 0;
56  cbuf = (unsigned char *)malloc(mseek);
57  nread = mseek;
58  ipos = iseek;
59 
60  /* Loop until grib message is found. */
61  while (*lgrib == 0 && nread == mseek)
62  {
63  /* Read partial section. */
64  fseek(lugb, ipos, SEEK_SET);
65  nread = fread(cbuf, sizeof(unsigned char), mseek, lugb);
66  lim = nread - 8;
67 
68  /* Look for 'grib...' in partial section. */
69  for (k = 0; k < lim; k++)
70  {
71  /* Look at the first 4 bytes - should be 'GRIB'. */
72  gbit(cbuf, &start, k * BYTE, 4 * BYTE);
73 
74  /* Look at the 8th byte, it has the GRIB version. */
75  gbit(cbuf, &vers, (k + 7) * BYTE, 1 * BYTE);
76 
77  /* If the message starts with 'GRIB', and is version 1 or
78  * 2, then this is a GRIB message. */
79  if (start == 1196575042 && (vers == 1 || vers == 2))
80  {
81  /* Find the length of the message. */
82  if (vers == 1)
83  gbit(cbuf, &lengrib, (k + 4) * BYTE, 3 * BYTE);
84  if (vers == 2)
85  gbit(cbuf, &lengrib, (k + 12) * BYTE, 4 * BYTE);
86  LOG((4, "lengrib %ld", lengrib));
87 
88  /* Read the last 4 bytesof the message. */
89  fseek(lugb, ipos + k + lengrib - 4, SEEK_SET);
90  k4 = fread(&end, 4, 1, lugb);
91 
92  /* Look for '7777' at end of grib message. */
93  if (k4 == 1 && end == 926365495)
94  {
95  /* GRIB message found. */
96  *lskip = ipos + k;
97  *lgrib = lengrib;
98  LOG((4, "found end of message lengrib %ld", lengrib));
99  break;
100  }
101  }
102  }
103  ipos = ipos + lim;
104  }
105 
106  free(cbuf);
107 }
void gbit(unsigned char *in, g2int *iout, g2int iskip, g2int nbits)
Get bits - unpack bits: Extract arbitrary size values from a packed bit string, right justifying each...
Definition: gbits.c:20
int64_t g2int
Long integer type.
Definition: grib2.h:33
Header file with internal function prototypes NCEPLIBS-g2c library.
#define LOG(e)
Ignore logging to stdout.
Definition: grib2_int.h:426
#define BYTE
Number of bits in a byte.
Definition: grib2_int.h:47
void seekgb(FILE *lugb, g2int iseek, g2int mseek, g2int *lskip, g2int *lgrib)
Search a file for the next GRIB Message.
Definition: seekgb.c:46