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