1 : #include <stdio.h>
2 : #include <stdlib.h>
3 : #include "grib2.h"
4 :
5 0 : void seekgb(FILE *lugb,g2int iseek,g2int mseek,g2int *lskip,g2int *lgrib)
6 : //$$$ SUBPROGRAM DOCUMENTATION BLOCK
7 : //
8 : // SUBPROGRAM: seekgb Searches a file for the next GRIB message.
9 : // PRGMMR: Gilbert ORG: W/NP11 DATE: 2002-10-28
10 : //
11 : // ABSTRACT: This subprogram searches a file for the next GRIB Message.
12 : // The search is done starting at byte offset iseek of the file referenced
13 : // by lugb for mseek bytes at a time.
14 : // If found, the starting position and length of the message are returned
15 : // in lskip and lgrib, respectively.
16 : // The search is terminated when an EOF or I/O error is encountered.
17 : //
18 : // PROGRAM HISTORY LOG:
19 : // 2002-10-28 GILBERT Modified from Iredell's skgb subroutine
20 : //
21 : // USAGE: seekgb(FILE *lugb,g2int iseek,g2int mseek,int *lskip,int *lgrib)
22 : // INPUT ARGUMENTS:
23 : // lugb - FILE pointer for the file to search. File must be
24 : // opened before this routine is called.
25 : // iseek - number of bytes in the file to skip before search
26 : // mseek - number of bytes to search at a time
27 : // OUTPUT ARGUMENTS:
28 : // lskip - number of bytes to skip from the beggining of the file
29 : // to where the GRIB message starts
30 : // lgrib - number of bytes in message (set to 0, if no message found)
31 : //
32 : // ATTRIBUTES:
33 : // LANGUAGE: C
34 : //
35 : //$$$
36 : {
37 : g2int ret;
38 : g2int k,k4,ipos,nread,lim,start,vers,end,lengrib;
39 : unsigned char *cbuf;
40 :
41 : // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
42 0 : *lgrib=0;
43 0 : cbuf=(unsigned char *)malloc(mseek);
44 0 : nread=mseek;
45 0 : ipos=iseek;
46 :
47 : // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
48 : // LOOP UNTIL GRIB MESSAGE IS FOUND
49 :
50 0 : while (*lgrib==0 && nread==mseek) {
51 :
52 : // READ PARTIAL SECTION
53 :
54 0 : ret=fseek(lugb,ipos,SEEK_SET);
55 0 : nread=fread(cbuf,sizeof(unsigned char),mseek,lugb);
56 0 : lim=nread-8;
57 :
58 : // LOOK FOR 'GRIB...' IN PARTIAL SECTION
59 :
60 0 : for (k=0;k<lim;k++) {
61 0 : gbit(cbuf,&start,(k+0)*8,4*8);
62 0 : gbit(cbuf,&vers,(k+7)*8,1*8);
63 0 : if (start==1196575042 && (vers==1 || vers==2)) {
64 : // LOOK FOR '7777' AT END OF GRIB MESSAGE
65 0 : if (vers == 1) gbit(cbuf,&lengrib,(k+4)*8,3*8);
66 0 : if (vers == 2) gbit(cbuf,&lengrib,(k+12)*8,4*8);
67 0 : ret=fseek(lugb,ipos+k+lengrib-4,SEEK_SET);
68 0 : k4=fread(&end,sizeof(g2int),1,lugb);
69 0 : if (k4 == 1 && end == 926365495) { //GRIB message found
70 0 : *lskip=ipos+k;
71 0 : *lgrib=lengrib;
72 0 : break;
73 : }
74 : }
75 : }
76 0 : ipos=ipos+lim;
77 : }
78 :
79 0 : free(cbuf);
80 0 : }
|