NCEPLIBS-g2c  1.7.0
seekgb.c
Go to the documentation of this file.
1 
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include "grib2_int.h"
8 
10 #define BITS_PER_BYTE 8
11 
38 void
39 seekgb(FILE *lugb, g2int iseek, g2int mseek, g2int *lskip, g2int *lgrib)
40 {
41  g2int k, k4, ipos, nread, lim, start, vers, lengrib;
42  int end;
43  unsigned char *cbuf;
44 
45  *lgrib = 0;
46  cbuf = (unsigned char *)malloc(mseek);
47  nread = mseek;
48  ipos = iseek;
49 
50  /* Loop until grib message is found. */
51  while (*lgrib == 0 && nread == mseek)
52  {
53  /* Read partial section. */
54  fseek(lugb, ipos, SEEK_SET);
55  nread = fread(cbuf, sizeof(unsigned char), mseek, lugb);
56  lim = nread - 8;
57 
58  /* Look for 'grib...' in partial section. */
59  for (k = 0; k < lim; k++)
60  {
61  /* Look at the first 4 bytes - should be 'GRIB'. */
62  gbit(cbuf, &start, k * BITS_PER_BYTE, 4 * BITS_PER_BYTE);
63 
64  /* Look at the 8th byte, it has the GRIB version. */
65  gbit(cbuf, &vers, (k + 7) * BITS_PER_BYTE, 1 * BITS_PER_BYTE);
66 
67  /* If the message starts with 'GRIB', and is version 1 or
68  * 2, then this is a GRIB message. */
69  if (start == 1196575042 && (vers == 1 || vers == 2))
70  {
71  /* Find the length of the message. */
72  if (vers == 1)
73  gbit(cbuf, &lengrib, (k + 4) * BITS_PER_BYTE, 3 * BITS_PER_BYTE);
74  if (vers == 2)
75  gbit(cbuf, &lengrib, (k + 12) * BITS_PER_BYTE, 4 * BITS_PER_BYTE);
76 
77  /* Read the last 4 bytesof the message. */
78  fseek(lugb, ipos + k + lengrib - 4, SEEK_SET);
79  k4 = fread(&end, 4, 1, lugb);
80 
81  /* Look for '7777' at end of grib message. */
82  if (k4 == 1 && end == 926365495)
83  {
84  /* GRIB message found. */
85  *lskip = ipos + k;
86  *lgrib = lengrib;
87  break;
88  }
89  }
90  }
91  ipos = ipos + lim;
92  }
93 
94  free(cbuf);
95 }
grib2_int.h
Header file with internal function prototypes NCEPLIBS-g2c library.
gbit
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
g2int
int64_t g2int
Long integer type.
Definition: grib2.h:28
seekgb
void seekgb(FILE *lugb, g2int iseek, g2int mseek, g2int *lskip, g2int *lgrib)
This subprogram searches a file for the next GRIB Message.
Definition: seekgb.c:39
BITS_PER_BYTE
#define BITS_PER_BYTE
8 bits per byte.
Definition: seekgb.c:10