Debian Codegraph @

frmts/grib/degrib/g2clib/seekgb.c

raw
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "grib2.h"
4
5 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 beginning 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 = 0,lengrib;
39 unsigned char *cbuf;
40
41 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
42 *lgrib=0;
43 cbuf=(unsigned char *)malloc(mseek);
44 nread=mseek;
45 ipos=iseek;
46
47 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
48 // LOOP UNTIL GRIB MESSAGE IS FOUND
49
50 while (*lgrib==0 && nread==mseek) {
51
52 // READ PARTIAL SECTION
53
54 /* ret= */ fseek(lugb,ipos,SEEK_SET);
55 nread=(int)fread(cbuf,sizeof(unsigned char),mseek,lugb);
56 lim=nread-8;
57
58 // LOOK FOR 'GRIB...' IN PARTIAL SECTION
59
60 for (k=0;k<lim;k++) {
61 gbit(cbuf,&start,(k+0)*8,4*8);
62 gbit(cbuf,&vers,(k+7)*8,1*8);
63 if (start==1196575042 && (vers==1 || vers==2)) {
64 // LOOK FOR '7777' AT END OF GRIB MESSAGE
65 if (vers == 1) gbit(cbuf,&lengrib,(k+4)*8,3*8);
66 if (vers == 2) gbit(cbuf,&lengrib,(k+12)*8,4*8);
67 /* ret= */ fseek(lugb,ipos+k+lengrib-4,SEEK_SET);
68 // Hard code to 4 instead of sizeof(g2int)
69 k4=(g2int)fread(&end,4,1,lugb);
70 if (k4 == 1 && end == 926365495) { //GRIB message found
71 *lskip=ipos+k;
72 *lgrib=lengrib;
73 break;
74 }
75 }
76 }
77 ipos=ipos+lim;
78 }
79
80 free(cbuf);
81 }