示例#1
0
文件: dfp.c 项目: schwehr/hdf4
/*--------------------------------------------------------------------------
 NAME
    DFPIopen -- open/reopen file for palette interface
 USAGE
    int32 DFPIopen(filename,acc_mode)
        char *filename;         IN: name of HDF file
        intn acc_mode;            IN: type of access to open file with
 RETURNS
    HDF file handle on success, FAIL on failure.
 DESCRIPTION
    Open/reopen a file for the DFP interface to work with.
 GLOBAL VARIABLES
    Refset, Readref, Lastfile
 COMMENTS, BUGS, ASSUMPTIONS
    This is a hook for someday providing more efficient ways to
    reopen a file, to avoid re-reading all the headers
 EXAMPLES
 REVISION LOG
--------------------------------------------------------------------------*/
PRIVATE int32
DFPIopen(const char *filename, intn acc_mode)
{
  CONSTR(FUNC, "DFPIopen");
  int32       file_id;
  int32       ret_value = SUCCEED;

  /* use reopen if same file as last time - more efficient */
  if (HDstrncmp(Lastfile, filename, DF_MAXFNLEN) || (acc_mode == DFACC_CREATE))
    {
      /* treat create as different file */
      if ((file_id = Hopen(filename, acc_mode, 0)) == FAIL)
        HGOTO_ERROR(DFE_BADOPEN, FAIL);
      Refset = 0;   /* no ref to get set for this file */
      Readref = 0;
    }     /* end if */
  else if ((file_id = Hopen(filename, acc_mode, 0)) == FAIL)
    HGOTO_ERROR(DFE_BADOPEN, FAIL);

    /* remember filename, so reopen may be used next time if same file */
  HDstrncpy(Lastfile, filename, DF_MAXFNLEN);

  ret_value = (file_id);

done:
  if(ret_value == FAIL)   
    { /* Error condition cleanup */

    } /* end if */

  /* Normal function cleanup */

  return ret_value;
}   /* end DFPIopen() */
示例#2
0
文件: he_main.c 项目: schwehr/hdf4
int32
getElement(int desc, char **pdata)
{
    int32       length;
    int32       fid;

    length = he_desc[desc].length;

    /* alloc memory to read the element in */
    *pdata = (char *) HDmalloc(length);
    if (*pdata == NULL)
        return FAIL;

    /* read in the element and check for error */
    if ((fid = Hopen(he_file, DFACC_READ, 0)) == 0)
      {
          HEprint(stderr, 0);
          return FAIL;
      }
    if (Hgetelement(fid, he_desc[desc].tag, he_desc[desc].ref, (unsigned char *) (*pdata)) < 0)
      {
          HDfree(*pdata);
          fprintf(stderr, "Cannot read element.\n");
          return FAIL;
      }
    Hclose(fid);
    return length;
}
示例#3
0
/*
   ** NAME
   **   DFopen -- open HDF file
   ** USAGE
   **   DF *DFopen(name, acc_mode, ndds)
   **   char* name;             IN: name of file to open
   **   int acc_mode;           IN: DFACC_READ, DFACC_WRITE, DFACC_CREATE,
   **                               DFACC_ALL
   **   int ndds;               IN: number of DDs in a block
   ** RETURNS
   **   DF ptr to open file on success, NULL on failure with DFerror set
   ** DESCRIPTION
   **   Open an HDF file, if it exists.  If file does not exist and write
   **   access requested, create file.
   ** GLOBAL VARIABLES
   ** COMMENTS, BUGS, ASSUMPTIONS
   **   The pointer returned by DFopen is NOT a reference to a DF.  It is
   **   just a place keeper for the new type of file handle.  Any program that
   **   relies on the contents of a DF returned by DFopen must be re-written.
   ** EXAMPLES
   ** REVISION LOG
 */
DF         *
DFopen(char *name, int acc_mode, int ndds)
{
    if (DFIcheck(DFlist) == 0)
      {
          DFerror = DFE_TOOMANY;
          return (NULL);
      }
    else
        DFerror = DFE_NONE;

    DFaccmode = acc_mode | DFACC_READ;
    DFid = Hopen(name, DFaccmode, (int16) ndds);

    if (DFid == -1)
      {
          DFerror = (int)HEvalue(1);
          return (NULL);
      }
    else
      {
          /*
             DFlist = makedf(DFid);
           */
          DFlist = (DF *) & DFid;
          return (DFlist);
      }
}
示例#4
0
static void
test_vgisinternal()
{
    int32   fid, vgroup_id;
    intn    is_internal = FALSE;
    int32   vref = -1;
    intn    ii, status;
    char testfile[H4_MAX_NC_NAME] = "";
    char    internal_array2[2] = {TRUE, TRUE};
    intn    num_errs = 0;     /* number of errors so far */

    /* Use a GR file to test Vgisinternal on internal vgroups */

    /* The file GR_FILE is an existing file in the test_files directory,
       make_datafilename builds the file name with correct path */
    if (make_datafilename(GR_FILE, testfile, H4_MAX_NC_NAME) != FAIL)
    {
	/* Open the old GR file and initialize the V interface */
	fid = Hopen(testfile, DFACC_READ, 0);
	CHECK_VOID(fid, FAIL, "Hopen: grtdfui83.hdf");
	status = Vstart(fid);
	CHECK_VOID(status, FAIL, "Vstart");

	ii = 0;
	while ((vref = Vgetid(fid, vref)) != FAIL)
	{     /* until no more vgroups */
	    vgroup_id = Vattach(fid, vref, "r"); /* attach to vgroup */

	    /* Test that the current vgroup is or is not internal as specified
	       in the array internal_array2 */
	    is_internal = Vgisinternal(vgroup_id);
	    CHECK_VOID(is_internal, FAIL, "Vgisinternal");
  	    VERIFY_VOID(is_internal, internal_array2[ii], "Vgisinternal");

	    status = Vdetach(vgroup_id);
	    CHECK_VOID(status, FAIL, "Vdetach");

	    ii++; /* increment vgroup index */
	}

	/* Terminate access to the V interface and close the file */
	status = Vend(fid);
	CHECK_VOID(status, FAIL, "Vend");
	status = Hclose(fid);
	CHECK_VOID(status, FAIL, "Hclose");
    }
    else
    {
	fprintf(stderr, "ERROR>>> Unable to make filename for %s\n", GR_FILE);
	H4_FAILED()
    }
}   /* test_vgisinternal */
示例#5
0
文件: he_main.c 项目: schwehr/hdf4
int
deleteDesc(int desc)
{
    int32       fid;

    if ((fid = Hopen(he_file, DFACC_WRITE, 0)) == 0)
      {
          HEprint(stderr, 0);
          return FAIL;
      }

    if (Hdeldd(fid, he_desc[desc].tag, he_desc[desc].ref) == FAIL)
      {
          HEprint(stderr, 0);
          return FAIL;
      }
    return Hclose(fid);
}
示例#6
0
/*
   ** NAME
   **   DFishdf -- is this an HDF file?
   ** USAGE
   **   int DFishdf(filename)
   **   char *filename;         IN: name of file to check
   ** RETURNS
   **   0 if it is an HDF file, -1 if it is not.
   ** DESCRIPTION
   **   Determine whether file is an HDF file.
   ** GLOBAL VARIABLES
   ** COMMENTS, BUGS, ASSUMPTIONS
   ** EXAMPLES
   ** REVISION LOG
 */
int
DFishdf(char *filename)
{
    int32       dummy;

    DFerror = DFE_NONE;

    dummy = Hopen(filename, DFACC_READ, 0);
    if (dummy == -1)
      {
          DFerror = (int)HEvalue(1);
          return (-1);
      }
    else
      {
          Hclose(dummy);
          return (0);
      }
}
示例#7
0
/******************************************************************************
!Description: 'CreateOuptut' creates a new output file.
 
!Input Parameters:
 file_name      output file name

!Output Parameters:
 (returns)      status:
                  'true' = okay
                  'false' = error return

!Team Unique Header:

!Design Notes:
*****************************************************************************/
bool CreateOutput(char *file_name, char *input_header, char *output_header)
{
  int32 hdf_file_id;
  /* Create the file with HDF open */
  hdf_file_id = Hopen(file_name, DFACC_CREATE, DEF_NDDS); 
  if (hdf_file_id == HDF_ERROR) {
    RETURN_ERROR("creating output file", "CreateOutput", false); 
  }

  /* Close the file */
  Hclose(hdf_file_id);

  // Copy input header file
  std::ifstream  src(input_header);
  std::ofstream  dst(output_header);

   dst << src.rdbuf();


  return true;
}
示例#8
0
bool CreateOutput(char *file_name)
/* 
!C******************************************************************************

!Description: 'CreateOuptut' creates a new HDF output file.
 
!Input Parameters:
 file_name      output file name

!Output Parameters:
 (returns)      status:
                  'true' = okay
		  'false' = error return

!Team Unique Header:

 ! Design Notes:
   1. An error status is returned when:
       a. the creation of the output file failes.
   2. Error messages are handled with the 'LOG_RETURN_ERROR' macro.
   3. The output file is in HDF format and closed after it is created.

!END****************************************************************************
*/
{
  int32 hdf_file_id;

  /* Create the file with HDF open */

  hdf_file_id = Hopen(file_name, DFACC_CREATE, DEF_NDDS); 
  if(hdf_file_id == HDF_ERROR) {
    LOG_RETURN_ERROR("creating output file", "CreateOutput", false); 
  }

  /* Close the file */

  Hclose(hdf_file_id);

  return true;
}
示例#9
0
int list_main(const char* infname,
         const char* outfname, 
         options_t *options)
{
    list_table_t *list_tbl=NULL;     /* list of objects */
    dim_table_t  *td1=NULL;       /* dimensions */
    dim_table_t  *td2=NULL;       /* dimensions */
    int32        sd_id=FAIL,      /* SD interface identifier */
                 sd_out=FAIL,     /* SD interface identifier */
                 gr_id=FAIL,      /* GR interface identifier */
                 gr_out=FAIL,     /* GR interface identifier */
                 infile_id=FAIL,
                 outfile_id=FAIL;
    int          i;
    const char*  err;

   /*-------------------------------------------------------------------------
    * initialize tables
    *-------------------------------------------------------------------------
    */
    
    list_table_init(&list_tbl);
    dim_table_init(&td1);
    dim_table_init(&td2);
    
   /*-------------------------------------------------------------------------
    * open the input file for read and initialize interfaces
    *-------------------------------------------------------------------------
    */
   
    if ((infile_id  = Hopen (infname,DFACC_READ,(int16)0))==FAIL)
    {
        printf("Cannot open file <%s>\n",infname);
        goto out;
    }
    if ((sd_id  = SDstart (infname, DFACC_READ))==FAIL)
    {
        printf( "Could not start SD for <%s>\n",infname);
        goto out;
    }
    if ((gr_id  = GRstart (infile_id))==FAIL)
    {
        printf( "Could not start GR for <%s>\n",infname);
        goto out;
    }
   
   /*-------------------------------------------------------------------------
    * create the output file and initialize interfaces
    *-------------------------------------------------------------------------
    */

    if ( options->trip==1 ) 
    {
        if ((outfile_id = Hopen (outfname,DFACC_CREATE,(int16)0))==FAIL)
        {
            printf("Cannot create file <%s>\n",outfname);
            goto out;
        }
        if ((sd_out = SDstart (outfname, DFACC_WRITE))==FAIL)
        {
            printf( "Could not start GR for <%s>\n",outfname);
            goto out;
        }
        
        if ((gr_out = GRstart (outfile_id))==FAIL)
        {
            printf( "Could not start GR for <%s>\n",outfname);
            goto out;
        }
    } /* options->trip==1 */

    
    if (options->verbose && options->trip==0)
        printf("Building list of objects in %s...\n",infname);


   /*-------------------------------------------------------------------------
    * iterate tru HDF interfaces 
    *-------------------------------------------------------------------------
    */

    if (options->verbose) 
    {
        printf("-----------------------------------------------\n");
        printf(" Chunk   Filter(compression) Name\n");
        printf("-----------------------------------------------\n");
    }
    
    if (list_vg (infile_id,outfile_id,sd_id,sd_out,gr_id,gr_out,list_tbl,td1,td2,options)<0) 
        goto out;
    if (list_gr (infile_id,outfile_id,gr_id,gr_out,list_tbl,options)<0) 
        goto out;
    if (list_sds(infile_id,outfile_id,sd_id,sd_out,list_tbl,td1,td2,options)<0) 
        goto out;
    if (list_vs (infile_id,outfile_id,list_tbl,options)<0) 
        goto out;
    if (list_glb(infile_id,outfile_id,sd_id,sd_out,gr_id,gr_out,list_tbl,options)<0) 
        goto out;
    if (list_pal(infname,outfname,list_tbl,options)<0) 
        goto out;
    if (list_an (infile_id,outfile_id,options)<0) 
        goto out;
    
    
    if ( options->trip==1 ) 
    {
        match_dim(sd_id,sd_out,td1,td2,options);
    }
    

   /*-------------------------------------------------------------------------
    * check for objects in the file table:
    *   1) the input object names are present in the file
    *   2) they are valid objects (SDS or GR)
    * check only if selected objects are given (all==0)
    *-------------------------------------------------------------------------
    */
    
    if ( options->trip==0 ) 
    {
        if (options->verbose)
            printf("Searching for objects to modify...\n");
        
        for ( i = 0; i < options->op_tbl->nelems; i++) 
        {
            char* obj_name=options->op_tbl->objs[i].objpath;
            if (options->verbose)
                printf(PFORMAT1,"","",obj_name);
            
            /* the input object names are present in the file and are valid */
            err=list_table_check(list_tbl,obj_name);
            if (err!=NULL)
            {
                printf("\nError: <%s> %s in file <%s>. Exiting...\n",obj_name,err,infname);
                goto out;
            }
            if (options->verbose)
                printf("...Found\n");
        }
    }
    
    
   /*-------------------------------------------------------------------------
    * close interfaces
    *-------------------------------------------------------------------------
    */
    if (GRend (gr_id)==FAIL)
        printf( "Failed to close GR interface <%s>\n", infname);
    if (SDend (sd_id)==FAIL)
        printf( "Failed to close file <%s>\n", infname);
    if (Hclose (infile_id)==FAIL)
        printf( "Failed to close file <%s>\n", infname);

    if ( options->trip==1 ) 
    {
        if (GRend (gr_out)==FAIL)
            printf( "Failed to close GR interface <%s>\n", outfname);
        if (SDend (sd_out)==FAIL)
            printf( "Failed to close file <%s>\n", outfname);
        if (Hclose (outfile_id)==FAIL)
            printf( "Failed to close file <%s>\n", outfname);
    }


   /*-------------------------------------------------------------------------
    * free tables
    *-------------------------------------------------------------------------
    */
  
    list_table_free(list_tbl);
    dim_table_free(td1);
    dim_table_free(td2);
    
    return SUCCEED;
    
out:
    
    if (list_tbl!=NULL)
        list_table_free(list_tbl);
    if (td1!=NULL)
        dim_table_free(td1);
    if (td2!=NULL)
        dim_table_free(td2);
    if (gr_id!=FAIL)
    {
        if (GRend (gr_id)==FAIL)
            printf( "Failed to close GR interface <%s>\n", infname);
    }
    if (gr_out!=FAIL)
    {
        if (GRend (gr_out)==FAIL)
            printf( "Failed to close GR interface <%s>\n", outfname);
    }
    if (sd_id!=FAIL)
    {
        if (SDend (sd_id)==FAIL)
            printf( "Failed to close SD interface for <%s>\n", infname);
        
    }
    if (sd_out!=FAIL)
    {
        if (SDend (sd_out)==FAIL)
            printf( "Failed to close SD interface for <%s>\n", outfname);
    }
    if (infile_id!=FAIL)
    {
        if (Hclose (infile_id)==FAIL)
            printf( "Failed to close file <%s>\n", infname);
    }
    if (outfile_id!=FAIL)
    {
        if (Hclose (outfile_id)==FAIL)
            printf( "Failed to close file <%s>\n", outfname);
        
    }
    
    return FAIL;
    
}
示例#10
0
文件: hdfunpac.c 项目: schwehr/hdf4
int
main(int argc, char *argv[])
{
    int32       infile, aid, ret;
    char       *filename;
    char        datafilename[DF_MAXFNLEN];

    uint16      tag;
    uint16      ref;
    int32       offset, fileoffset;
    int32       length;
    int16       special;

    /* Get invocation name of program */
    progname = *argv++;
    argc--;

    /* parse arguments */
    while (argc > 0 && **argv == '-')
      {
          switch ((*argv)[1])
            {
                case 'd':
                    argc--;
                    argv++;
                    if (argc > 0)
                      {
                          strcpy(datafilename, *argv++);
                          argc--;
                      }
                    else
                      {
                          usage();
                          exit(1);
                      }
                    break;
                default:
                    usage();
                    exit(1);
            }
      }

    if (argc == 1)
      {
          filename = *argv++;
          argc--;
      }
    else
      {
          usage();
          exit(1);
      }

    if (datafilename[0] == '\0')
        strcpy(datafilename, DefaultDatafile);

    /* Check to make sure input file is HDF */
    ret = (int) Hishdf(filename);
    if (ret == FALSE)
      {
          error("given file is not an HDF file\n");
      }

    /* check if datafile already exists.  If so, set offset to its length. */
    {
        struct stat buf;
        if (stat(datafilename, &buf) == 0)
          {
              printf("External file %s already exists.  Using append mode.\n", datafilename);
              fileoffset = (int32)buf.st_size;
          }
        else
            fileoffset = 0;
    }

    /* Open HDF file */
    infile = Hopen(filename, DFACC_RDWR, 0);
    if (infile == FAIL)
      {
          error("Can't open the HDF file\n");
      }

    /* Process the file */
    ret = aid = Hstartread(infile, DFTAG_SD, DFREF_WILDCARD);
    while (ret != FAIL)
      {
          /*
           * Get data about the current one
           */
          ret = Hinquire(aid, NULL, &tag, &ref, &length, &offset, NULL, NULL, &special);

          /* check the tag value since external element object are returned the same. */
          if (tag == DFTAG_SD)
            {
                printf("moving Scientific Data (%d,%d) to %s\n", tag, ref, datafilename);
                ret = HXcreate(infile, tag, ref, datafilename, fileoffset, length);
                fileoffset += length;
            }

          /*
           * Move to the next one
           */
          ret = Hnextread(aid, DFTAG_SD, DFREF_WILDCARD, DF_CURRENT);
      }

    /*
     * Close the access element
     */
    ret = Hendaccess(aid);
    if (ret == FAIL)
        hdferror();

    /* done; close files */
    Hclose(infile);
    return (0);
}
示例#11
0
文件: vd_ex5.c 项目: hdfeos/ocaml-hdf
void main(void)
{

    char    vdata_name[MAX_NC_NAME], vdata_class[MAX_NC_NAME];
    char    fields[60];
    int32   file_id, vdata_id, istat;
    int32   n_records, interlace, vdata_size, vdata_ref;
    int     bufsz = (2 * sizeof(float32) + sizeof(char) \
                     + sizeof(int16)) * NRECORDS;
    int    i;
    uint8  databuf[((2 * sizeof(float32)) + sizeof(char) \
                    + sizeof(int16)) * NRECORDS];
    VOIDP fldbufptrs[4];
    float32 itemp[NRECORDS], ispeed[NRECORDS];
    int16   iheight[NRECORDS];
    char    idents[NRECORDS];

    /* Open the HDF file. */
    file_id = Hopen("VD_Ex4.hdf", DFACC_READ, 0);

    /* Initialize the Vset interface. */
    istat = Vstart(file_id);

    /*
    * Get the reference number for the first Vdata in
    * the file.
    */
    vdata_ref = -1;
    vdata_ref = VSgetid(file_id, vdata_ref);

    /* Attach to the first Vdata in read mode. */
    vdata_id = VSattach(file_id, vdata_ref, "r");
    for (i=0; i<60; i++)
        fields[i] = '\0';
    /* Get the list of field names. */
    istat =VSinquire(vdata_id, &n_records, &interlace,
                     fields, &vdata_size, vdata_name);
    printf("files: %s, n_records: %d, vdata_size: %d\n",
           fields, n_records, vdata_size);
    /* Get the class. */
    istat = VSgetclass(vdata_id, vdata_class);

    /* Determine the fields that will be read. */
    istat = VSsetfields(vdata_id, fields);

    /* Print the Vdata information. */
    printf("Current Vdata name: %s \nCurrent Vdata class: %s.\n",
           vdata_name, vdata_class);

    /* Read the data. */
    istat = VSread(vdata_id, (VOIDP)databuf, n_records,
                   FULL_INTERLACE);
    /* set fldbufptrs and unpack field values */
    fldbufptrs[0] = &idents[0];
    fldbufptrs[1] = &ispeed[0];
    fldbufptrs[2] = &iheight[0];
    fldbufptrs[3] = &itemp[0];

    istat = VSfpack(vdata_id, _HDF_VSUNPACK, fields, databuf,
                    bufsz, n_records, "Ident,Speed,Height,Temp",
                    fldbufptrs);
    printf("     Temp      Height     Speed      Ident\n");
    for (i=0; i < n_records; i++) {
        printf("   %6.2f    %6d      %6.2f       %c\n",
               itemp[i],iheight[i],ispeed[i],idents[i]);
    }
    /* Detach from the Vdata, close the interface and the file. */
    istat = VSdetach(vdata_id);
    istat = Vend(file_id);
    istat = Hclose(file_id);

}
示例#12
0
文件: he_main.c 项目: schwehr/hdf4
int
updateDesc(void)
{
    int32      fid;
    int32       groupID;
    int32       aid, status;
    int i, j;

    if ((fid = Hopen(he_file, DFACC_READ, 0)) == 0)
      {
          printf("failed opening\n");
          HEprint(stdout, 0);
          return FAIL;
      }

    aid = Hstartread(fid, DFTAG_WILDCARD, DFREF_WILDCARD);
    if (aid == FAIL)
      {
          HEprint(stderr, 0);
          return FAIL;
      }

    status = SUCCEED;
    for (i = 0; (i < HE_DESC_SZ) && (status != FAIL); i++)
      {
          Hinquire(aid, NULL, &he_desc[i].tag, &he_desc[i].ref, &he_desc[i].length,
                   &he_desc[i].offset, NULL, (int16 *) NULL, (int16 *) NULL);
          status = Hnextread(aid, DFTAG_WILDCARD, DFREF_WILDCARD, DF_CURRENT);
      }
    he_numDesc = i;

    /* get informations about the groups */
    he_numGrp = 0;
    for (i = 0; i < he_numDesc; i++)
      {
          if (isGrp(he_desc[i].tag))
            {
                he_grp[he_numGrp].desc = i;
/*                he_grp[he_numGrp].size = (int) (he_desc[i].length / sizeof(tag_ref));
                he_grp[he_numGrp].ddList = (tag_ref_ptr) HDmalloc(he_desc[i].length);
*/
                he_grp[he_numGrp].size = (int) (he_desc[i].length / 4);
                he_grp[he_numGrp].ddList = (tag_ref_ptr) HDmalloc(he_grp[he_numGrp].size*sizeof(tag_ref));

                if (!he_grp[he_numGrp].ddList)
                  {
                      fprintf(stderr, "Out of memory. Closing file.\n");
                      closeFile(1);     /* keep the backup */
                      return FAIL;
                  }
                groupID = DFdiread(fid, he_desc[i].tag, he_desc[i].ref);
                if (groupID < 0)
                  {
                      HEprint(stderr, 0);
                      return FAIL;
                  }
                for (j = 0; j < he_grp[he_numGrp].size; j++)
                    DFdiget(groupID, &he_grp[he_numGrp].ddList[j].tag,
                            &he_grp[he_numGrp].ddList[j].ref);

                he_numGrp++;
            }
      }
    Hendaccess(aid);
    Hclose(fid);
    return SUCCEED;
}
示例#13
0
GDALDataset *HDF4Dataset::Open( GDALOpenInfo * poOpenInfo )

{
    if( !Identify( poOpenInfo ) )
        return NULL;

    CPLMutexHolderD(&hHDF4Mutex);

/* -------------------------------------------------------------------- */
/*      Try opening the dataset.                                        */
/* -------------------------------------------------------------------- */

    // Attempt to increase maximum number of opened HDF files.
#ifdef HDF4_HAS_MAXOPENFILES
    intn nCurrMax = 0;
    intn nSysLimit = 0;

    if ( SDget_maxopenfiles(&nCurrMax, &nSysLimit) >= 0
         && nCurrMax < nSysLimit )
    {
        /*intn res = */SDreset_maxopenfiles( nSysLimit );
    }
#endif /* HDF4_HAS_MAXOPENFILES */

    int32 hHDF4 = Hopen(poOpenInfo->pszFilename, DFACC_READ, 0);

    if( hHDF4 <= 0 )
        return NULL;

    Hclose( hHDF4 );

/* -------------------------------------------------------------------- */
/*      Create a corresponding GDALDataset.                             */
/* -------------------------------------------------------------------- */
    // Release mutex otherwise we will deadlock with GDALDataset own mutex.
    CPLReleaseMutex(hHDF4Mutex);
    HDF4Dataset *poDS = new HDF4Dataset();
    CPLAcquireMutex(hHDF4Mutex, 1000.0);

    if( poOpenInfo->fpL != NULL )
    {
        VSIFCloseL(poOpenInfo->fpL);
        poOpenInfo->fpL = NULL;
    }

/* -------------------------------------------------------------------- */
/*          Open HDF SDS Interface.                                     */
/* -------------------------------------------------------------------- */
    poDS->hSD = SDstart( poOpenInfo->pszFilename, DFACC_READ );

    if ( poDS->hSD == -1 )
    {
      // Release mutex otherwise we will deadlock with GDALDataset own mutex.
        CPLReleaseMutex(hHDF4Mutex);
        delete poDS;
        CPLAcquireMutex(hHDF4Mutex, 1000.0);
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "Failed to open HDF4 file \"%s\" for SDS reading.",
                  poOpenInfo->pszFilename );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*              Now read Global Attributes.                             */
/* -------------------------------------------------------------------- */
    if ( poDS->ReadGlobalAttributes( poDS->hSD ) != CE_None )
    {
        // Release mutex otherwise we will deadlock with GDALDataset own mutex.
        CPLReleaseMutex(hHDF4Mutex);
        delete poDS;
        CPLAcquireMutex(hHDF4Mutex, 1000.0);
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "Failed to read global attributes from HDF4 file \"%s\".",
                  poOpenInfo->pszFilename );
        return NULL;
    }

    poDS->SetMetadata( poDS->papszGlobalMetadata, "" );

/* -------------------------------------------------------------------- */
/*              Determine type of file we read.                         */
/* -------------------------------------------------------------------- */
    const char *pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata,
                                             "Signature");

    if ( pszValue != NULL && EQUAL( pszValue, pszGDALSignature ) )
    {
        poDS->iSubdatasetType = H4ST_GDAL;
        poDS->pszSubdatasetType = "GDAL_HDF4";
    }

    else if ( (pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata,
                                            "Title")) != NULL
         && EQUAL( pszValue, "SeaWiFS Level-1A Data" ) )
    {
        poDS->iSubdatasetType = H4ST_SEAWIFS_L1A;
        poDS->pszSubdatasetType = "SEAWIFS_L1A";
    }

    else if ( (pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata,
                                            "Title")) != NULL
        && EQUAL( pszValue, "SeaWiFS Level-2 Data" ) )
    {
        poDS->iSubdatasetType = H4ST_SEAWIFS_L2;
        poDS->pszSubdatasetType = "SEAWIFS_L2";
    }

    else if ( (pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata,
                                            "Title")) != NULL
        && EQUAL( pszValue, "SeaWiFS Level-3 Standard Mapped Image" ) )
    {
        poDS->iSubdatasetType = H4ST_SEAWIFS_L3;
        poDS->pszSubdatasetType = "SEAWIFS_L3";
    }

    else if ( (pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata,
                                            "L1 File Generated By")) != NULL
        && STARTS_WITH_CI(pszValue, "HYP version ") )
    {
        poDS->iSubdatasetType = H4ST_HYPERION_L1;
        poDS->pszSubdatasetType = "HYPERION_L1";
    }

    else
    {
        poDS->iSubdatasetType = H4ST_UNKNOWN;
        poDS->pszSubdatasetType = "UNKNOWN";
    }

/* -------------------------------------------------------------------- */
/*  If we have HDF-EOS dataset, process it here.                        */
/* -------------------------------------------------------------------- */
    int32 aiDimSizes[H4_MAX_VAR_DIMS] = {};  // TODO: Get this off of the stack.
    int32 iRank = 0;
    int32 iNumType = 0;
    int32 nAttrs = 0;
    bool bIsHDF = true;

    // Sometimes "HDFEOSVersion" attribute is not defined and we will
    // determine HDF-EOS datasets using other records
    // (see ReadGlobalAttributes() method).
    if ( poDS->bIsHDFEOS
         || CSLFetchNameValue(poDS->papszGlobalMetadata, "HDFEOSVersion") )
    {
/* -------------------------------------------------------------------- */
/*  Process swath layers.                                               */
/* -------------------------------------------------------------------- */
        hHDF4 = SWopen( poOpenInfo->pszFilename, DFACC_READ );
        if( hHDF4 < 0)
        {
            // Release mutex otherwise we will deadlock with GDALDataset own
            // mutex.
            CPLReleaseMutex(hHDF4Mutex);
            delete poDS;
            CPLAcquireMutex(hHDF4Mutex, 1000.0);
            CPLError( CE_Failure, CPLE_OpenFailed,
                      "Failed to open HDF-EOS file \"%s\" for swath reading.",
                      poOpenInfo->pszFilename );
            return NULL;
        }
        int32 nStrBufSize = 0;
        int32 nSubDatasets =
            SWinqswath(poOpenInfo->pszFilename, NULL, &nStrBufSize);

#ifdef DEBUG
        CPLDebug( "HDF4", "Number of HDF-EOS swaths: %d",
                  static_cast<int>( nSubDatasets ) );
#endif

        if ( nSubDatasets > 0 && nStrBufSize > 0 )
        {
            char *pszSwathList =
                static_cast<char *>( CPLMalloc( nStrBufSize + 1 ) );
            SWinqswath( poOpenInfo->pszFilename, pszSwathList, &nStrBufSize );
            pszSwathList[nStrBufSize] = '\0';

#ifdef DEBUG
            CPLDebug( "HDF4", "List of HDF-EOS swaths: %s", pszSwathList );
#endif

            char **papszSwaths =
                CSLTokenizeString2( pszSwathList, ",", CSLT_HONOURSTRINGS );
            CPLFree( pszSwathList );

            if ( nSubDatasets != CSLCount(papszSwaths) )
            {
                CSLDestroy( papszSwaths );
                // Release mutex otherwise we will deadlock with GDALDataset own
                // mutex.
                CPLReleaseMutex(hHDF4Mutex);
                delete poDS;
                CPLAcquireMutex(hHDF4Mutex, 1000.0);
                CPLDebug( "HDF4", "Cannot parse list of HDF-EOS grids." );
                return NULL;
            }

            for( int32 i = 0; i < nSubDatasets; i++)
            {
                const int32 hSW = SWattach( hHDF4, papszSwaths[i] );

                const int32 nFields
                    = SWnentries( hSW, HDFE_NENTDFLD, &nStrBufSize );
                char *pszFieldList = static_cast<char *>(
                    CPLMalloc( nStrBufSize + 1 ) );
                int32 *paiRank = static_cast<int32 *>(
                    CPLMalloc( nFields * sizeof(int32) ) );
                int32 *paiNumType = static_cast<int32 *>(
                    CPLMalloc( nFields * sizeof(int32) ) );

                SWinqdatafields( hSW, pszFieldList, paiRank, paiNumType );

#ifdef DEBUG
                {
                    char * const pszTmp =
                        SPrintArray( GDT_UInt32, paiRank, nFields, "," );

                    CPLDebug( "HDF4", "Number of data fields in swath %d: %d",
                              static_cast<int>( i ),
                              static_cast<int>( nFields ) );
                    CPLDebug( "HDF4", "List of data fields in swath %d: %s",
                              static_cast<int>( i ), pszFieldList );
                    CPLDebug( "HDF4", "Data fields ranks: %s", pszTmp );

                    CPLFree( pszTmp );
                }
#endif

                char **papszFields = CSLTokenizeString2( pszFieldList, ",",
                                                         CSLT_HONOURSTRINGS );

                char szTemp[256] = {'\0'};  // TODO: Get this off the stack.
                for( int32 j = 0; j < nFields; j++ )
                {
                    SWfieldinfo( hSW, papszFields[j], &iRank, aiDimSizes,
                                 &iNumType, NULL );

                    if ( iRank < 2 )
                        continue;

                    // Add field to the list of GDAL subdatasets.
                    const int nCount = CSLCount( poDS->papszSubDatasets ) / 2;
                    snprintf( szTemp, sizeof(szTemp),
                              "SUBDATASET_%d_NAME", nCount + 1 );
                    // We will use the field index as an identificator.
                    poDS->papszSubDatasets =
                        CSLSetNameValue( poDS->papszSubDatasets, szTemp,
                                CPLSPrintf("HDF4_EOS:EOS_SWATH:\"%s\":%s:%s",
                                           poOpenInfo->pszFilename,
                                           papszSwaths[i], papszFields[j]) );

                    snprintf( szTemp, sizeof(szTemp),
                              "SUBDATASET_%d_DESC", nCount + 1 );
                    char *pszString = SPrintArray( GDT_UInt32, aiDimSizes,
                                                   iRank, "x" );
                    poDS->papszSubDatasets =
                        CSLSetNameValue( poDS->papszSubDatasets, szTemp,
                                         CPLSPrintf( "[%s] %s %s (%s)",
                                                     pszString,
                                         papszFields[j],
                                         papszSwaths[i],
                                         poDS->GetDataTypeName(iNumType) ) );
                    CPLFree( pszString );
                    szTemp[0] = '\0';
                }

                CSLDestroy( papszFields );
                CPLFree( paiNumType );
                CPLFree( paiRank );
                CPLFree( pszFieldList );
                SWdetach( hSW );
            }

            CSLDestroy( papszSwaths );
        }
        SWclose( hHDF4 );

/* -------------------------------------------------------------------- */
/*  Process grid layers.                                                */
/* -------------------------------------------------------------------- */
        hHDF4 = GDopen( poOpenInfo->pszFilename, DFACC_READ );
        nSubDatasets = GDinqgrid( poOpenInfo->pszFilename, NULL, &nStrBufSize );

#ifdef DEBUG
        CPLDebug( "HDF4", "Number of HDF-EOS grids: %d",
                  static_cast<int>( nSubDatasets ) );
#endif

        if ( nSubDatasets > 0 && nStrBufSize > 0 )
        {
            char *pszGridList
                = static_cast<char *>( CPLMalloc( nStrBufSize + 1 ) );
            GDinqgrid( poOpenInfo->pszFilename, pszGridList, &nStrBufSize );

#ifdef DEBUG
            CPLDebug( "HDF4", "List of HDF-EOS grids: %s", pszGridList );
#endif

            char **papszGrids =
                CSLTokenizeString2( pszGridList, ",", CSLT_HONOURSTRINGS );
            CPLFree( pszGridList );

            if ( nSubDatasets != CSLCount(papszGrids) )
            {
                CSLDestroy( papszGrids );
                GDclose( hHDF4 );
                // Release mutex otherwise we will deadlock with GDALDataset own
                // mutex.
                CPLReleaseMutex(hHDF4Mutex);
                delete poDS;
                CPLAcquireMutex(hHDF4Mutex, 1000.0);
                CPLDebug( "HDF4", "Cannot parse list of HDF-EOS grids." );
                return NULL;
            }

            for( int32 i = 0; i < nSubDatasets; i++)
            {
                const int32 hGD = GDattach( hHDF4, papszGrids[i] );

                const int32 nFields
                    = GDnentries( hGD, HDFE_NENTDFLD, &nStrBufSize );
                char *pszFieldList = static_cast<char *>(
                    CPLMalloc( nStrBufSize + 1 ) );
                int32 *paiRank = static_cast<int32 *>(
                    CPLMalloc( nFields * sizeof(int32) ) );
                int32 *paiNumType = static_cast<int32 *>(
                    CPLMalloc( nFields * sizeof(int32) ) );

                GDinqfields( hGD, pszFieldList, paiRank, paiNumType );

#ifdef DEBUG
                {
                    char* pszTmp =
                            SPrintArray( GDT_UInt32, paiRank, nFields, "," );
                    CPLDebug( "HDF4", "Number of fields in grid %d: %d",
                              static_cast<int>( i ),
                              static_cast<int>( nFields ) );
                    CPLDebug( "HDF4", "List of fields in grid %d: %s",
                              static_cast<int>( i ), pszFieldList );
                    CPLDebug( "HDF4", "Fields ranks: %s", pszTmp );
                    CPLFree( pszTmp );
                }
#endif

                char **papszFields = CSLTokenizeString2( pszFieldList, ",",
                                                  CSLT_HONOURSTRINGS );

                char szTemp[256];
                for( int32 j = 0; j < nFields; j++ )
                {
                    GDfieldinfo( hGD, papszFields[j], &iRank, aiDimSizes,
                                 &iNumType, NULL );

                    if ( iRank < 2 )
                        continue;

                    // Add field to the list of GDAL subdatasets
                    const int nCount = CSLCount( poDS->papszSubDatasets ) / 2;
                    snprintf( szTemp, sizeof(szTemp),
                              "SUBDATASET_%d_NAME", nCount + 1 );
                    // We will use the field index as an identificator.
                    poDS->papszSubDatasets =
                        CSLSetNameValue(poDS->papszSubDatasets, szTemp,
                                CPLSPrintf( "HDF4_EOS:EOS_GRID:\"%s\":%s:%s",
                                            poOpenInfo->pszFilename,
                                            papszGrids[i], papszFields[j]));

                    snprintf( szTemp, sizeof(szTemp),
                              "SUBDATASET_%d_DESC", nCount + 1 );
                    char *pszString = SPrintArray( GDT_UInt32, aiDimSizes,
                                                   iRank, "x" );
                    poDS->papszSubDatasets =
                        CSLSetNameValue( poDS->papszSubDatasets, szTemp,
                                         CPLSPrintf("[%s] %s %s (%s)",
                                                    pszString,
                                             papszFields[j],
                                             papszGrids[i],
                                             poDS->GetDataTypeName(iNumType)) );
                    CPLFree( pszString );
                }

                CSLDestroy( papszFields );
                CPLFree( paiNumType );
                CPLFree( paiRank );
                CPLFree( pszFieldList );
                GDdetach( hGD );
            }

            CSLDestroy( papszGrids );
        }
        GDclose( hHDF4 );

        bIsHDF = ( nSubDatasets == 0 ); // Try to read as HDF
    }

    char szName[VSNAMELENMAX + 1];

    if( bIsHDF )
    {

/* -------------------------------------------------------------------- */
/*  Make a list of subdatasets from SDSs contained in input HDF file.   */
/* -------------------------------------------------------------------- */
        int32 nDatasets = 0;

        if ( SDfileinfo( poDS->hSD, &nDatasets, &nAttrs ) != 0 )
            return NULL;

        char szTemp[256] = {'\0'};  // TODO: Get this off the stack.
        const char *pszName = NULL;

        for( int32 i = 0; i < nDatasets; i++ )
        {
            const int32 iSDS = SDselect( poDS->hSD, i );
            if ( SDgetinfo( iSDS, szName, &iRank, aiDimSizes, &iNumType,
                            &nAttrs) != 0 )
                return NULL;

            if ( iRank == 1 )  // Skip 1D datsets
                    continue;

            // Do sort of known datasets. We will display only image bands
            if ( (poDS->iSubdatasetType == H4ST_SEAWIFS_L1A ) &&
                      !STARTS_WITH_CI(szName, "l1a_data") )
                    continue;
            else
                pszName = szName;

            // Add datasets with multiple dimensions to the list of GDAL
            // subdatasets.
            const int nCount = CSLCount( poDS->papszSubDatasets ) / 2;
            snprintf( szTemp, sizeof(szTemp),
                      "SUBDATASET_%d_NAME", nCount + 1 );
            // We will use SDS index as an identificator, because SDS names
            // are not unique. Filename also needed for further file opening
            poDS->papszSubDatasets = CSLSetNameValue(
                  poDS->papszSubDatasets,
                  szTemp,
                  CPLSPrintf( "HDF4_SDS:%s:\"%s\":%ld", poDS->pszSubdatasetType,
                              poOpenInfo->pszFilename,
                              static_cast<long>( i ) ) );
            snprintf( szTemp, sizeof(szTemp),
                      "SUBDATASET_%d_DESC", nCount + 1 );
            char *pszString = SPrintArray( GDT_UInt32, aiDimSizes, iRank, "x" );
            poDS->papszSubDatasets = CSLSetNameValue(
                poDS->papszSubDatasets,
                szTemp,
                CPLSPrintf( "[%s] %s (%s)", pszString,
                            pszName, poDS->GetDataTypeName(iNumType)) );
            CPLFree( pszString );

            SDendaccess( iSDS );
            szTemp[0] = '\0';
        }

        SDend( poDS->hSD );
        poDS->hSD = 0;
    }

/* -------------------------------------------------------------------- */
/*      Build a list of raster images. Note, that HDF-EOS dataset may   */
/*      contain a raster image as well.                                 */
/* -------------------------------------------------------------------- */

    hHDF4 = Hopen(poOpenInfo->pszFilename, DFACC_READ, 0);
    poDS->hGR = GRstart( hHDF4 );

    if ( poDS->hGR != -1 )
    {
        if ( GRfileinfo( poDS->hGR, &poDS->nImages, &nAttrs ) == -1 )
        {
            // Release mutex otherwise we will deadlock with GDALDataset own
            // mutex.
            CPLReleaseMutex(hHDF4Mutex);
            GRend( poDS->hGR );
            poDS->hGR = 0;
            Hclose( hHDF4 );
            delete poDS;
            CPLAcquireMutex(hHDF4Mutex, 1000.0);
            return NULL;
        }

        char szTemp[256] = {'\0'};  // TODO: Get this off the stack.
        for( int32 i = 0; i < poDS->nImages; i++ )
        {
            const int32 iGR = GRselect( poDS->hGR, i );

            // iRank in GR interface has another meaning. It represents number
            // of samples per pixel. aiDimSizes has only two dimensions.
            int32 iInterlaceMode = 0;
            if ( GRgetiminfo( iGR, szName, &iRank, &iNumType, &iInterlaceMode,
                              aiDimSizes, &nAttrs ) != 0 )
            {
                // Release mutex otherwise we will deadlock with GDALDataset
                // own mutex.
                CPLReleaseMutex(hHDF4Mutex);
                GRend( poDS->hGR );
                poDS->hGR = 0;
                Hclose( hHDF4 );
                delete poDS;
                CPLAcquireMutex(hHDF4Mutex, 1000.0);
                return NULL;
            }
            const int nCount = CSLCount( poDS->papszSubDatasets ) / 2;
            snprintf( szTemp, sizeof(szTemp),
                      "SUBDATASET_%d_NAME", nCount + 1 );
            poDS->papszSubDatasets = CSLSetNameValue(poDS->papszSubDatasets,
                szTemp,CPLSPrintf( "HDF4_GR:UNKNOWN:\"%s\":%ld",
                                   poOpenInfo->pszFilename,
                                   static_cast<long>( i ) ) );
            snprintf( szTemp, sizeof(szTemp),
                      "SUBDATASET_%d_DESC", nCount + 1 );
            char *pszString = SPrintArray( GDT_UInt32, aiDimSizes, 2, "x" );
            poDS->papszSubDatasets = CSLSetNameValue(poDS->papszSubDatasets,
                szTemp, CPLSPrintf( "[%sx%ld] %s (%s)", pszString,
                                    static_cast<long>( iRank ),
                                    szName, poDS->GetDataTypeName(iNumType)) );
            CPLFree( pszString );

            GRendaccess( iGR );
            szTemp[0] = '\0';
        }

        GRend( poDS->hGR );
        poDS->hGR = 0;
    }

    Hclose( hHDF4 );

    poDS->nRasterXSize = poDS->nRasterYSize = 512; // XXX: bogus values

    // Make sure we don't try to do any pam stuff with this dataset.
    poDS->nPamFlags |= GPF_NOSAVE;

/* -------------------------------------------------------------------- */
/*      If we have single subdataset only, open it immediately          */
/* -------------------------------------------------------------------- */
    if ( CSLCount( poDS->papszSubDatasets ) / 2 == 1 )
    {
        char *pszSDSName = CPLStrdup( CSLFetchNameValue( poDS->papszSubDatasets,
                                                         "SUBDATASET_1_NAME" ));
        // Release mutex otherwise we will deadlock with GDALDataset own mutex.
        CPLReleaseMutex(hHDF4Mutex);
        delete poDS;
        poDS = NULL;

        GDALDataset* poRetDS = reinterpret_cast<GDALDataset*>(
            GDALOpen( pszSDSName, poOpenInfo->eAccess ) );
        CPLFree( pszSDSName );

        CPLAcquireMutex(hHDF4Mutex, 1000.0);

        if (poRetDS)
        {
            poRetDS->SetDescription(poOpenInfo->pszFilename);
        }

        return poRetDS;
    }
    else
    {
/* -------------------------------------------------------------------- */
/*      Confirm the requested access is supported.                      */
/* -------------------------------------------------------------------- */
        if( poOpenInfo->eAccess == GA_Update )
        {
            // Release mutex otherwise we will deadlock with GDALDataset own
            // mutex.
            CPLReleaseMutex(hHDF4Mutex);
            delete poDS;
            CPLAcquireMutex(hHDF4Mutex, 1000.0);

            CPLError( CE_Failure, CPLE_NotSupported,
                      "The HDF4 driver does not support update access to "
                      "existing datasets." );
            return NULL;
        }

    }

    return poDS;
}
int main( )
{
   /************************* Variable declaration **************************/

   intn   status_n;     /* returned status for functions returning an intn  */
   int32  status_32,    /* returned status for functions returning an int32 */
          file_id, vgroup_id, vgroup_ref, vdata_id, vdata_ref,
	  num_of_records, num_of_vals_per_rec, record_pos,
          obj_index,    /* index of an object within a vgroup */
          num_of_pairs, /* number of tag/ref number pairs, i.e., objects */
          obj_tag, obj_ref,     /* tag/ref number of an HDF object */
          vgroup_pos = 0;       /* position of a vgroup in the file */
   float32 databuf[N_RECORDS][N_VALS_PER_REC];
   int16 rec_num;

   /********************** End of variable declaration ***********************/

   char FIELDNAME_LIST[MAX_FIELDNAME_LIST_LENGTH];
   memset(FIELDNAME_LIST, 0x00, MAX_FIELDNAME_LIST_LENGTH);
   int i;
   for (i = 0; i < N_VALS_PER_REC; i++) {
	   char buffer[256];
	   if (i == 0) {
		   sprintf(buffer, "%d", i);
	   } else {
		   sprintf(buffer, " %d", i);
	   }
	   strcat(FIELDNAME_LIST, buffer);
   }
   file_id = Hopen (FILE_NAME, DFACC_READ, 0);

   status_n = Vstart (file_id);

   vgroup_ref = -1;

   vgroup_ref = Vgetid (file_id, vgroup_ref);
   if (vgroup_ref == -1) exit(1);
   vgroup_ref = Vgetid (file_id, vgroup_ref);
   if (vgroup_ref == -1) exit(1);

   vgroup_id = Vattach (file_id, vgroup_ref, "r"); 

   num_of_pairs = Vntagrefs (vgroup_id);

   if (num_of_pairs > 0)
   {
	   printf ("\nVgroup #%d contains:\n", vgroup_pos);
	   for (obj_index = 0; obj_index < num_of_pairs; obj_index++)
	   {
		   status_n = Vgettagref (vgroup_id, obj_index, &obj_tag, &obj_ref);
		   printf ("tag = %d, ref = %d", obj_tag, obj_ref);


		   if (Visvg (vgroup_id, obj_ref))
			   printf ("  <-- is a vgroup\n");
		   else if (Visvs (vgroup_id, obj_ref)) {
			   printf ("  <-- is a vdata\n");
			   vdata_ref = VSfind (file_id, VDATA_NAME);
			   vdata_id = VSattach (file_id, vdata_ref, "r");
			   status_n = VSsetfields (vdata_id, FIELDNAME_LIST);
			   record_pos = VSseek (vdata_id, RECORD_INDEX);
			   num_of_records =
				   VSread (vdata_id, (uint8 *)databuf, N_RECORDS, FULL_INTERLACE);
			   for (rec_num = 0; rec_num < num_of_records; rec_num++)
			   {
				   for (num_of_vals_per_rec = 0; num_of_vals_per_rec < N_VALS_PER_REC; num_of_vals_per_rec++) {
					   printf ("%6.2f\n", databuf[rec_num][num_of_vals_per_rec]);

				   }
			   }
		   }
		   else {
			   printf ("  <-- neither vdata nor vgroup\n");
		   }
	   } /* for */
   } /* if */

   else
	   printf ("Vgroup #%d contains no HDF objects\n", vgroup_pos);

   /*
    * Terminate access to the current vgroup.
    */
   status_32 = Vdetach (vgroup_id);

   /*
    * Move to the next vgroup position.
    */
   vgroup_pos++;

   /*
   * Terminate access to the V interface and close the file.
   */
   status_n = Vend (file_id);
   status_n = Hclose (file_id);
   return 0;
}
示例#15
0
static int do_groups(void) 
{
     
     int32 vg0_id,    /* vgroup identifier */
           vg1_id,    /* vgroup identifier */
           vg2_id,    /* vgroup identifier */
           file1_id;  /* HDF file identifier */
     
     /* create a HDF file */
     if ((file1_id = Hopen (FILE7_NAME, DFACC_CREATE, (int16)0))<0)
     {
         printf("Error: Could not create file <%s>\n",FILE7_NAME);
         return FAIL;
     }
     
     /* initialize the V interface */
     if (Vstart (file1_id)==FAIL)
     {
         printf( "Could not start VG\n");
         return FAIL;
     }
     
     /* create a vgroup */
     vg0_id = Vattach (file1_id, -1, "w");
     if (Vsetname (vg0_id, "g0")==FAIL)
     {
         printf( "Could not name group\n");
         goto out;
     }
     
     /* create the second vgroup */
     vg1_id = Vattach (file1_id, -1, "w");
     if (Vsetname (vg1_id, "g1")==FAIL)
     {
         printf( "Could not name group\n");
         goto out;
     }
     
     /* create the third vgroup */
     vg2_id = Vattach (file1_id, -1, "w");
     if (Vsetname (vg2_id, "g1.1")==FAIL)
     {
         printf( "Could not name group\n");
         goto out;
     }
  
     if (Vinsert (vg0_id, vg1_id)==FAIL)
     {
         printf( "Could not insert VG\n");
         goto out;
     }
     
     if (Vinsert (vg0_id, vg2_id)==FAIL)
     {
         printf( "Could not insert VG\n");
         goto out;
     }
     
     if (Vinsert (vg1_id, vg2_id)==FAIL)
     {
         printf( "Could not insert VG\n");
         goto out;
     }
     
     if (Vinsert (vg2_id, vg1_id)==FAIL)
     {
         printf( "Could not insert VG\n");
         goto out;
     }
     
     /* terminate access to the vgroup */
     if (Vdetach (vg0_id)==FAIL)
     {
         printf( "Could not close group\n");
         goto out;
     }
     
     /* terminate access to the vgroup */
     if (Vdetach (vg1_id)==FAIL)
     {
         printf( "Could not close group\n");
         goto out;
     }
     
     /* terminate access to the vgroup */
     if (Vdetach (vg2_id)==FAIL)
     {
         printf( "Could not close group\n");
         goto out;
     }
     
     /* terminate access to the V interface */
     if (Vend (file1_id)==FAIL)
     {
         printf( "Could not end VG\n");
         goto out;
     }
     
     /* close the HDF file */
     if (Hclose (file1_id)==FAIL)
     {
         printf( "Could not close file\n");
         return FAIL;
     }
     
     return SUCCEED;
     
out:
     printf("Error...Exiting...\n");
     return FAIL;
     
}
示例#16
0
int do_lone(char* file_name, int do_diffs)
{
    char    sds_name[]  = "lone";
    int32   rank        = 1;
    int32   dim_sds[1]  = {5};             /* dimension of the data set */
    int32   data[5]     = {1, 2, 3, 4, 5};
    int32   start[1];                      /* start position to write for each dimension */
    int32   edges[1];                      /* number of elements to be written along each dimension */
    int32   sds_id;
    int32   dim_id;
    int32   sd_id;

    if ( do_diffs )
    {
 
        data[1] = data[2] = 0;
    }
    
    sd_id  = SDstart(file_name, DFACC_CREATE);
    
    /* create the SDS */
    if ((sds_id = SDcreate (sd_id, sds_name, DFNT_INT32, rank, dim_sds))<0)
    {
        printf( "Could not create SDS <%s>\n",sds_name);
        goto fail;
    }
    
    dim_id = SDgetdimid(sds_id, 0);
    SDsetdimname(dim_id, sds_name);

    /* define the location and size of the data to be written to the data set */
    start[0] = 0;
    edges[0] = 5;
    
    /* write the stored data to the data set */
    if (SDwritedata (sds_id, start, NULL, edges, (VOIDP)data)==FAIL)
    {
        printf( "Failed to set write for SDS <%s>\n", sds_name);
        goto fail;
    } 
    
    
    SDendaccess(sds_id);


    /* create the SDS */
    if ((sds_id = SDcreate (sd_id, "sds", DFNT_INT32, rank, dim_sds))<0)
    {
        printf( "Could not create SDS <%s>\n");
        goto fail;
    }

    if (SDwritedata (sds_id, start, NULL, edges, (VOIDP)data)==FAIL)
    {
        printf( "Failed to set write for SDS <%s>\n");
        goto fail;
    } 

    SDendaccess(sds_id);

    SDend(sd_id);


    {
        int32 file1_id;      /*  HDF file identifier */ 
        int32 an_id;        /* AN interface identifier */
        int32 file_label_id;  /* file label identifier */
           
        /* open file */
        if ((file1_id = Hopen (file_name, DFACC_WRITE, (int16)0))<0)
        {
            printf("Error: Could not open file <%s>\n",file_name);
            return FAIL;
        }
        
        /* Initialize the AN interface */
        an_id = ANstart (file1_id);
              
        /* Create the file label */
        file_label_id = ANcreatef (an_id, AN_FILE_LABEL);
        
        /* Write the annotations to the file label */
        if (ANwriteann (file_label_id,FILE_LABEL_TXT,strlen (FILE_LABEL_TXT))==FAIL)
        {
            printf( "Could not write AN\n");
            return FAIL;
        }

        /* Terminate access to annotation */
        if (ANendaccess (file_label_id)==FAIL)
        {
            printf( "Could not end AN\n");
            return FAIL;
        }
        
        /* Terminate access to the AN interface */
        if (ANend (an_id)==FAIL)
        {
            printf( "Could not end AN\n");
            return FAIL;
        }
        

        /* close the HDF file */
        if (Hclose (file1_id)==FAIL)
        {
            printf( "Could not close file\n");
            return FAIL;
        }
  
    }
    
    return SUCCEED;

fail:
    SDend(sd_id);
    return FAIL;
}
示例#17
0
//// [[Rcpp::export]]
int binlist(int x) {
 int     numbins = 0, *binnums = NULL;
  int     i;
  int     file_id,vdata_ref, vdata_id,numrecs,pvd_id;
  char PARAM[] = "chlor_a";
  initbin();
  
  /* Open the HDF file. */
  file_id = Hopen("S1998001.L3b_DAY_CHL.main", DFACC_READ, 0);
  if(file_id == FAIL){
    fprintf(stderr,"-E- %s line %d: Hopen(%s,DFACC_READ,0) failed.\n",
      __FILE__,__LINE__,"S1998001.L3b_DAY_CHL.main");
    return(EXIT_FAILURE);
  }
  /* Initialize the Vdata interface. */
  if(Vstart(file_id) == FAIL){
    fprintf(stderr,"-E- %s line %d: Vstart(%d) failed.\n",
	    __FILE__,__LINE__,file_id);
    return(EXIT_FAILURE);
  }
  
  /* Open the "BinList" Vdata. */
  vdata_ref = VSfind(file_id,"BinList");
  if(vdata_ref == FAIL){
    fprintf(stderr,"-E- %s line %d: VSfind(%d,\"BinList\") failed.\n",
	    __FILE__,__LINE__,file_id);
    return(EXIT_FAILURE);
  }
  
  vdata_id = VSattach(file_id, vdata_ref, "r");
  if(vdata_id == FAIL){
    fprintf(stderr,"-E- %s line %d: VSattach(%d,%d,\"r\") failed.\n",
      __FILE__,__LINE__,file_id,vdata_ref);
    return(EXIT_FAILURE);
  }
  /* Find out how many bins are stored in this file. */
  numrecs = VSelts(vdata_id);
  if(numrecs == FAIL){
    fprintf(stderr,"-E- %s line %d: VSelts(%d) failed.\n",
	    __FILE__,__LINE__,vdata_id);
    return(EXIT_FAILURE);
  }
  
  // this doesn't seem to be necessary?
  /* Set up to read the fields in the BinList Vdata records. */
//  if(VSsetfields(vdata_id,BLIST_FIELDS) == FAIL){
//    fprintf(stderr,"-E- %s line %d: VSsetfields(%d,%s) failed.\n",
//	    __FILE__,__LINE__,vdata_id,BLIST_FIELDS);
//    return(EXIT_FAILURE);
//  }

  /* Open the parameter-specific Vdata. */
  vdata_ref = VSfind(file_id,PARAM);
  if(vdata_ref == 0){
    fprintf(stderr,"-E- %s line %d: VSfind(%d,\"%s\") failed.\n",
	    __FILE__,__LINE__,file_id,PARAM);
    return(EXIT_FAILURE);
  }
  pvd_id = VSattach(file_id, vdata_ref, "r");
  if(pvd_id == FAIL){
    fprintf(stderr,"-E- %s line %d: VSattach(%d,%d,\"r\") failed.\n",
	    __FILE__,__LINE__,file_id,vdata_ref);
    return(EXIT_FAILURE);
  }
    /* Set up to read the fields in the parameter-specific Vdata records. */
  {
    int len;
    len = 2*strlen(PARAM) + strlen("_sum,") + strlen("_sum_sq") + 1;
    param_fields = (char *)malloc(len);
    if(param_fields == NULL){
      fprintf(stderr,"-E- %s line %d: Memory allocation failed.\n",
        __FILE__,__LINE__);
      return(EXIT_FAILURE);
    }
    strcpy(param_fields,PARAM);
    strcat(param_fields,"_sum,");
    strcat(param_fields,PARAM);
    strcat(param_fields,"_sum_sq");
  }
  if(VSsetfields(pvd_id,param_fields) == FAIL){
    fprintf(stderr,"-E- %s line %d: VSsetfields(%d,%s) failed.\n",
	    __FILE__,__LINE__,pvd_id,param_fields);
    return(EXIT_FAILURE);
  }

  printf(param_fields);
  printf("\n");





  /* Output a header record to identify the fields written out below. */
  printf("%80s%15.15s %15.15s\n"," ",PARAM,PARAM);
  printf("    bin centerlat  centerlon");
  printf("     north     south       west       east");
  printf("    n   N         sum_obs sum_squared_obs          weight");
  printf("  time_trend_bits                     l2_flag_bits sel\n");
  printf("------- --------- ----------");
  printf(" --------- --------- ---------- ----------");
  printf(" ---- --- --------------- --------------- ---------------");
  printf(" ---------------- -------------------------------- ---\n");
 
 // for(i = 0; i < numbins; i++){
  for(i = 0; i < 10; i++){
    int   recno;

   // recno = binsearch(binnums[i],vdata_id,numrecs);
    recno = i;
    if(recno >= 0){
      double    n,s,w,e,clat,clon;

      /*
      Read the sum and sum-of-squares for the
      the specified parameter for this bin.
      */
      if(VSseek(pvd_id,recno) == FAIL){
        fprintf(stderr,"-E- %s line %d: VSseek(%d,%d) failed.\n",
  	__FILE__,__LINE__,pvd_id,recno);
	return(EXIT_FAILURE);
      }
      if(VSread(pvd_id,paramrec,1,FULL_INTERLACE) != 1){
        fprintf(stderr,"-E- %s line %d: ",__FILE__,__LINE__);
	fprintf(stderr,"VSread(%d,paramrec,1,FULL_INTERLACE) failed.\n",
		pvd_id);
        return(EXIT_FAILURE);
      }
      /*
      VSfpack() sets the global sum and sum_sq variables
      via the paramptrs pointer array.
      */
      if(
	 VSfpack(
		 pvd_id,_HDF_VSUNPACK,param_fields,paramrec,PREC_SIZE,1,NULL,paramptrs
		 )
	 == FAIL){
        fprintf(stderr,"-E- %s line %d: ",__FILE__,__LINE__);
	fprintf(stderr,"VSfpack(%d, ...) failed.\n", pvd_id);
	return(EXIT_FAILURE);
      }

      /* Get the geographical coordinates associated with this bin. */
    //  bin2latlon(binnums[i],&clat,&clon);
    //  bin2bounds(binnums[i],&n,&s,&w,&e);

      /* Output the results. */
    //  printf("%7d %9.5f %10.5f %9.5f %9.5f %10.5f %10.5f ",
	  //   binnums[i],clat,clon,n,s,w,e);
    //  printf("%4d %3d ",nobs,nscenes);
    //  printf("% .8e % .8e % .8e ",sum,sum_sq,weights);
      printf("% .8e % .8e % .8e ",sum,sum_sq,0.0);
   //   printf("%.16s %.32s ",bitstr16(time_rec),bitstr32(flags_set));
   //   printf("%3d",sel_cat);
      printf("\n");
    }

  }

  if(VSdetach(pvd_id) == FAIL){
    fprintf(stderr,"-E- %s line %d: VSdetach(%d) failed.\n",
	    __FILE__,__LINE__,pvd_id);
    return(EXIT_FAILURE);
  }
  if(VSdetach(vdata_id) == FAIL){
    fprintf(stderr,"-E- %s line %d: VSdetach(%d) failed.\n",
	    __FILE__,__LINE__,vdata_id);
    return(EXIT_FAILURE);
  }
  if(Vend(file_id) == FAIL){
    fprintf(stderr,"-E- %s line %d: Vend(%d) failed.\n",
	    __FILE__,__LINE__,file_id);
    return(EXIT_FAILURE);
  }
  if(Hclose(file_id) == FAIL){
    fprintf(stderr,"-E- %s line %d: Hclose(%d) failed.\n",
	    __FILE__,__LINE__,file_id);
    return(EXIT_FAILURE);
  }

  free(param_fields);
  free(binnums);






   return 2;
}
示例#18
0
int main(void) 
{
 int32 sd1_id;        /* SD interface identifier */
 int32 sd2_id;        /* SD interface identifier */
 int32 sds1_id;       /* SDS identifier */
 int32 sds2_id;       /* SDS identifier */
 int32 dim_sizes[2];  /* sizes of the SDS dimensions */
 int32 start[2];      /* start location to write */
 int32 edges[2];      /* number of elements to write */
 int32 n_values;
 int32 buf1a[Y_LENGTH][X_LENGTH] = {{1,1},{1,1},{5,6}};
 int32 buf1b[Y_LENGTH][X_LENGTH] = {{1,2},{3,4},{5,6}};

 /* percent test: compare divide by zero, both zero */
 int32 buf2a[Y_LENGTH][X_LENGTH] = {{100,100},{100,0},{0,100}}; 
 int32 buf2b[Y_LENGTH][X_LENGTH] = {{120,80},{0,100},{0,50}};

 /* global attributes */
 char8 bufga1[] = "Storm_track_data1"; 
 char8 bufga2[] = "Storm_track_data2"; 
 float32 bufa1[2] = {1., 1.};
 float32 bufa2[2] = {1., 2.};

 /*vdata*/
 int32 file1_id; 
 int32 file2_id; 
 int32 vdata1_id;
 int32 vdata2_id;
 char8 vdata1_buf1 [N_RECORDS_1] = {'V', 'D', 'A', 'T', 'A'};
 char8 vdata1_buf2 [N_RECORDS_1] = {'X', 'D', 'A', 'T', 'A'};
 int32 vdata2_buf1  [N_RECORDS_2][ORDER_2] = {{1, 2, 3, 4}, {5, 6, 7, 8}};
 int32 vdata2_buf2  [N_RECORDS_2][ORDER_2] = {{1, 1, 1, 1}, {5, 6, 7, 8}};
 float32 vdata3_buf1[N_RECORDS_2][N_VALS_PER_REC]={{1,2,3,4,5,6},{7,8,9,10,11,12}}; 
 float32 vdata3_buf2[N_RECORDS_2][N_VALS_PER_REC]={{1,1,1,1,1,1},{7,8,9,10,11,12}}; 
 
/* Define the location and size of the data to be written to the data set*/
 start[0] = 0;
 start[1] = 0;
 edges[0] = Y_LENGTH;
 edges[1] = X_LENGTH;

/* Define the dimensions of the array to be created */
 dim_sizes[0] = Y_LENGTH;
 dim_sizes[1] = X_LENGTH;

/*-------------------------------------------------------------------------
 * SD data
 *-------------------------------------------------------------------------
 */

 
/* Create the files and initialize the SD interface */
 if ((sd1_id = SDstart (FILE1_NAME, DFACC_CREATE))==FAIL) 
     goto error;
 if ((sd2_id = SDstart (FILE2_NAME, DFACC_CREATE))==FAIL) 
     goto error;

/* Set a global attribute */
 n_values  = sizeof(bufga1);
 if ( SDsetattr (sd1_id, FILE_ATTR_NAME, DFNT_CHAR8, n_values, (VOIDP)bufga1)==FAIL) 
     goto error;
 if ( SDsetattr (sd2_id, FILE_ATTR_NAME, DFNT_CHAR8, n_values, (VOIDP)bufga2)==FAIL) 
     goto error;
  
/* Create the data sets */ 
 if ((sds1_id = SDcreate (sd1_id, "dset1", DFNT_INT32, RANK, dim_sizes))==FAIL) 
     goto error;
 if ((sds2_id = SDcreate (sd2_id, "dset1", DFNT_INT32, RANK, dim_sizes))==FAIL) 
     goto error;

/* Assign attribute */
 n_values  = 2;
 if ( SDsetattr (sds1_id, SDS_ATTR_NAME, DFNT_FLOAT32, n_values, (VOIDP)bufa1)==FAIL) 
     goto error;
 if ( SDsetattr (sds2_id, SDS_ATTR_NAME, DFNT_FLOAT32, n_values, (VOIDP)bufa2)==FAIL) 
     goto error;
 
/* Write the stored data to the data set */
 if ( SDwritedata (sds1_id, start, NULL, edges, (VOIDP)buf1a)==FAIL) 
     goto error;
 if ( SDwritedata (sds2_id, start, NULL, edges, (VOIDP)buf1b)==FAIL) 
     goto error;
 
/* Terminate access to the data set */
 if ( SDendaccess (sds1_id)==FAIL) 
     goto error;
 if ( SDendaccess (sds2_id)==FAIL) 
     goto error;

 /* Create another data set */ 
 if (( sds1_id = SDcreate (sd1_id, "dset2", DFNT_INT32, RANK, dim_sizes))==FAIL) 
     goto error;
 if (( sds2_id = SDcreate (sd2_id, "dset2", DFNT_INT32, RANK, dim_sizes))==FAIL) 
     goto error;
 if ( SDwritedata (sds1_id, start, NULL, edges, (VOIDP)buf1a)==FAIL) 
     goto error;
 if ( SDwritedata (sds2_id, start, NULL, edges, (VOIDP)buf1b)==FAIL) 
     goto error;
 if ( SDendaccess (sds1_id)==FAIL) 
     goto error;
 if ( SDendaccess (sds2_id)==FAIL) 
     goto error;

 /* data sets for -p test */ 
 if (( sds1_id = SDcreate (sd1_id, "dset3", DFNT_INT32, RANK, dim_sizes))==FAIL) 
     goto error;
 if (( sds2_id = SDcreate (sd2_id, "dset3", DFNT_INT32, RANK, dim_sizes))==FAIL) 
     goto error;
 if ( SDwritedata (sds1_id, start, NULL, edges, (VOIDP)buf2a)==FAIL) 
     goto error;
 if ( SDwritedata (sds2_id, start, NULL, edges, (VOIDP)buf2b)==FAIL) 
     goto error;
 if ( SDendaccess (sds1_id)==FAIL) 
     goto error;
 if ( SDendaccess (sds2_id)==FAIL) 
     goto error;


/*-------------------------------------------------------------------------
 * end SD 
 *-------------------------------------------------------------------------
 */
 
 /* Terminate access to the SD interface and close the file */
 if ( SDend (sd1_id)==FAIL) 
     goto error;
 if ( SDend (sd2_id)==FAIL) 
     goto error;



/*-------------------------------------------------------------------------
 * VD data 
 *-------------------------------------------------------------------------
 */

/* Open the HDF file for writing */
 if ((file1_id = Hopen (FILE1_NAME, DFACC_WRITE, 0))==FAIL) 
     goto error;
 if ((file2_id = Hopen (FILE2_NAME, DFACC_WRITE, 0))==FAIL) 
     goto error;
 
/* Initialize the VS interface */
 if ( Vstart (file1_id)==FAIL) 
     goto error;
 if ( Vstart (file2_id)==FAIL) 
     goto error;

/*-------------------------------------------------------------------------
 * VD data one field
 *-------------------------------------------------------------------------
 */
 
/* Create the first vdata and populate it with data from vdata1_buf */
 if (VHstoredata (file1_id, FIELD1_NAME, (uint8 *)vdata1_buf1, 
  N_RECORDS_1, DFNT_CHAR8, VDATA1_NAME, CLASS1_NAME)==FAIL) 
     goto error; 
 if (VHstoredata (file2_id, FIELD1_NAME, (uint8 *)vdata1_buf2, 
  N_RECORDS_1, DFNT_CHAR8, VDATA1_NAME, CLASS1_NAME)==FAIL) 
     goto error; 

/*-------------------------------------------------------------------------
 * VD data one field, order 4
 *-------------------------------------------------------------------------
 */
 
/* Create the second vdata and populate it with data from vdata2_buf */
 if ( VHstoredatam (file1_id, FIELD2_NAME, (uint8 *)vdata2_buf1, 
  N_RECORDS_2, DFNT_INT32, VDATA2_NAME, CLASS2_NAME, ORDER_2)==FAIL) 
     goto error;  
 if ( VHstoredatam (file2_id, FIELD2_NAME, (uint8 *)vdata2_buf2, 
  N_RECORDS_2, DFNT_INT32, VDATA2_NAME, CLASS2_NAME, ORDER_2)==FAIL) 
     goto error;   

/*-------------------------------------------------------------------------
 * VD data several fields
 *-------------------------------------------------------------------------
 */

/* Create a new vdata */
 if ((vdata1_id = VSattach (file1_id, -1, "w"))==FAIL) 
     goto error;
 if ((vdata2_id = VSattach (file2_id, -1, "w"))==FAIL) 
     goto error;

/* Set name and class name of the vdata */
 if ( VSsetname (vdata1_id, VDATA3_NAME)==FAIL) 
     goto error;
 if ( VSsetclass (vdata1_id, CLASS3_NAME)==FAIL) 
     goto error;
 if ( VSsetname (vdata2_id, VDATA3_NAME)==FAIL) 
     goto error;
 if ( VSsetclass (vdata2_id, CLASS3_NAME)==FAIL) 
     goto error;

/* Define fields */
 if ( VSfdefine (vdata1_id, FIELD3_NAME1, DFNT_FLOAT32, ORDER3_1 )==FAIL) 
     goto error;
 if ( VSfdefine (vdata1_id, FIELD3_NAME2, DFNT_FLOAT32, ORDER3_2 )==FAIL) 
     goto error;
 if ( VSfdefine (vdata1_id, FIELD3_NAME3, DFNT_FLOAT32, ORDER3_3 )==FAIL) 
     goto error;
 if ( VSsetfields (vdata1_id, FIELDNAME3_LIST )==FAIL) 
     goto error;
 if ( VSfdefine (vdata2_id, FIELD3_NAME1, DFNT_FLOAT32, ORDER3_1 )==FAIL) 
     goto error;
 if ( VSfdefine (vdata2_id, FIELD3_NAME2, DFNT_FLOAT32, ORDER3_2 )==FAIL) 
     goto error;
 if ( VSfdefine (vdata2_id, FIELD3_NAME3, DFNT_FLOAT32, ORDER3_3 )==FAIL) 
     goto error;
 if ( VSsetfields (vdata2_id, FIELDNAME3_LIST)==FAIL) 
     goto error;

/* Write the data with full interlacing mode */
 if ( VSwrite (vdata1_id, (uint8 *)vdata3_buf1, N_RECORDS_2, FULL_INTERLACE)==FAIL) 
     goto error;
 if ( VSwrite (vdata2_id, (uint8 *)vdata3_buf2, N_RECORDS_2, FULL_INTERLACE)==FAIL) 
     goto error;

 if ( VSdetach (vdata1_id)==FAIL) 
     goto error;
 if ( VSdetach (vdata2_id)==FAIL) 
     goto error;

/*-------------------------------------------------------------------------
 * end VD data 
 *-------------------------------------------------------------------------
 */
 
/* Terminate access to the VS interface and close the HDF file */
 if ( Vend (file1_id)==FAIL) 
     goto error;
 if ( Vend (file2_id)==FAIL) 
     goto error;
 if ( Hclose (file1_id)==FAIL) 
     goto error;
 if ( Hclose (file2_id)==FAIL) 
     goto error;

/*-------------------------------------------------------------------------
 * write 2 big files for hyperslab reading
 *-------------------------------------------------------------------------
 */
 if (do_big_file()==FAIL) 
     goto error;

/*-------------------------------------------------------------------------
 * groups
 *-------------------------------------------------------------------------
 */
 if (do_groups()==FAIL) 
     goto error;

 
 return 0;

error:

 printf("Error...Exiting...\n");

 return 1;

}
示例#19
0
文件: coda-hdf4.c 项目: stcorp/coda
int coda_hdf4_reopen(coda_product **product)
{
    coda_hdf4_product *product_file;

    product_file = (coda_hdf4_product *)malloc(sizeof(coda_hdf4_product));
    if (product_file == NULL)
    {
        coda_set_error(CODA_ERROR_OUT_OF_MEMORY, "out of memory (could not allocate %lu bytes) (%s:%u)",
                       sizeof(coda_hdf4_product), __FILE__, __LINE__);
        coda_close(*product);
        return -1;
    }
    product_file->filename = NULL;
    product_file->file_size = (*product)->file_size;
    product_file->format = coda_format_hdf4;
    product_file->root_type = NULL;
    product_file->product_definition = NULL;
    product_file->product_variable_size = NULL;
    product_file->product_variable = NULL;
    product_file->mem_size = 0;
    product_file->mem_ptr = NULL;
    product_file->is_hdf = 0;
    product_file->file_id = -1;
    product_file->gr_id = -1;
    product_file->sd_id = -1;
    product_file->an_id = -1;
    product_file->num_gr_file_attributes = 0;
    product_file->num_sd_file_attributes = 0;
    product_file->num_sds = 0;
    product_file->sds = NULL;
    product_file->num_images = 0;
    product_file->gri = NULL;
    product_file->num_vgroup = 0;
    product_file->vgroup = NULL;
    product_file->num_vdata = 0;
    product_file->vdata = NULL;

    product_file->filename = strdup((*product)->filename);
    if (product_file->filename == NULL)
    {
        coda_set_error(CODA_ERROR_OUT_OF_MEMORY, "out of memory (could not duplicate filename string) (%s:%u)",
                       __FILE__, __LINE__);
        coda_hdf4_close((coda_product *)product_file);
        coda_close(*product);
        return -1;
    }

    coda_close(*product);

    product_file->is_hdf = Hishdf(product_file->filename);      /* is this a real HDF4 file or a (net)CDF file */
    if (product_file->is_hdf)
    {
        product_file->file_id = Hopen(product_file->filename, DFACC_READ, 0);
        if (product_file->file_id == -1)
        {
            coda_set_error(CODA_ERROR_HDF4, NULL);
            coda_hdf4_close((coda_product *)product_file);
            return -1;
        }
        if (Vstart(product_file->file_id) != 0)
        {
            coda_set_error(CODA_ERROR_HDF4, NULL);
            coda_hdf4_close((coda_product *)product_file);
            return -1;
        }
        product_file->gr_id = GRstart(product_file->file_id);
        if (product_file->gr_id == -1)
        {
            coda_set_error(CODA_ERROR_HDF4, NULL);
            coda_hdf4_close((coda_product *)product_file);
            return -1;
        }
        product_file->an_id = ANstart(product_file->file_id);
        if (product_file->an_id == -1)
        {
            coda_set_error(CODA_ERROR_HDF4, NULL);
            coda_hdf4_close((coda_product *)product_file);
            return -1;
        }
    }
    product_file->sd_id = SDstart(product_file->filename, DFACC_READ);
    if (product_file->sd_id == -1)
    {
        coda_set_error(CODA_ERROR_HDF4, NULL);
        coda_hdf4_close((coda_product *)product_file);
        return -1;
    }
    product_file->root_type = NULL;

    if (init_SDSs(product_file) != 0)
    {
        coda_hdf4_close((coda_product *)product_file);
        return -1;
    }
    if (product_file->is_hdf)
    {
        if (init_GRImages(product_file) != 0)
        {
            coda_hdf4_close((coda_product *)product_file);
            return -1;
        }
        if (init_Vdatas(product_file) != 0)
        {
            coda_hdf4_close((coda_product *)product_file);
            return -1;
        }
        /* initialization of Vgroup entries should happen last, so we can build the structural tree */
        if (init_Vgroups(product_file) != 0)
        {
            coda_hdf4_close((coda_product *)product_file);
            return -1;
        }
    }

    if (coda_hdf4_create_root(product_file) != 0)
    {
        coda_hdf4_close((coda_product *)product_file);
        return -1;
    }

    *product = (coda_product *)product_file;

    return 0;
}
示例#20
0
int main( )
{
   /************************* Variable declaration **************************/

   intn  status_n;      /* returned status for functions returning an intn  */
   int32 status_32,     /* returned status for functions returning an int32 */
         file_id, vdata_id, vdata_ref,
         index = 0;     /* index of the vdata in the file - manually kept   */
   int8  found_fields;  /* TRUE if the specified fields exist in the vdata  */

   /********************** End of variable declaration **********************/

   /*
   * Open the HDF file for reading.
   */
   file_id = Hopen (FILE_NAME, DFACC_READ, 0);

   /*
   * Initialize the VS interface.
   */
   status_n = Vstart (file_id);

   /*
   * Set the reference number to -1 to start the search from 
   * the beginning of file.
   */
   vdata_ref = -1;

   /*
   * Assume that the specified fields are not found in the current vdata.
   */
   found_fields = FALSE;
   
   /*
   * Use VSgetid to obtain each vdata by its reference number then
   * attach to the vdata and search for the fields.  The loop
   * terminates when the last vdata is reached or when a vdata which
   * contains the fields listed in SEARCHED_FIELDS is found.  
   */
   while ((vdata_ref = VSgetid (file_id, vdata_ref)) != FAIL)
   {
      vdata_id = VSattach (file_id, vdata_ref, "r");
      if ((status_n = VSfexist (vdata_id, SEARCHED_FIELDS)) != FAIL)
      {
         found_fields = TRUE;
         break;
      }

      /*
      * Detach from the current vdata before continuing searching.
      */
      status_32 = VSdetach (vdata_id);

      index++;		/* advance the index by 1 for the next vdata */
   }
   
   /*
   * Print the index of the vdata containing the fields or a "not found" 
   * message if no such vdata is found.  Also detach from the vdata found.
   */
   if (!found_fields) 
      printf ("Fields Position and Temperature were not found.\n");
   else 
   {
      printf
     ("Fields Position and Temperature found in the vdata at position %d\n", 
       index);
      status_32 = VSdetach (vdata_id);
   }

   /*
   * Terminate access to the VS interface and close the HDF file.
   */
   status_n = Vend (file_id);
   status_32 = Hclose (file_id);
   return 0;
}
int main( )
{   
   /************************* Variable declaration **************************/

   intn  status_n;      /* returned status for functions returning an intn  */
   int32 status_32,     /* returned status for functions returning an int32 */
         file_id, vdata_ref, vdata_id,
         field_index,   /* index of a field within the vdata */
         n_vdattrs,     /* number of vdata attributes */
         n_fldattrs,    /* number of field attributes */
         vdata_type,    /* to hold the type of vdata's attribute */ 
         vdata_n_values,/* to hold the number of vdata's attribute values   */ 
         vdata_size,    /* to hold the size of vdata's attribute values     */ 
         field_type,    /* to hold the type of field's attribute            */ 
         field_n_values,/* to hold the number of field's attribute values   */ 
         field_size;    /* to hold the size of field's attribute values     */
   char  vd_attr[VATTR_N_VALUES] = {'A', 'B', 'C'};/* vdata attribute values*/
   int32 fld_attr[FATTR_N_VALUES] = {2, 4, 6, 8};  /* field attribute values*/
   char  vattr_buf[VATTR_N_VALUES];     /* to hold vdata attribute's values */
   int32 fattr_buf[FATTR_N_VALUES];     /* to hold field attribute's values */
   char  vattr_name[30],                /* name of vdata attribute */
         fattr_name[30];                /* name of field attribute */

   /********************** End of variable declaration **********************/

   /*
   * Open the HDF file for writing.
   */
   file_id = Hopen (FILE_NAME, DFACC_WRITE, 0);

   /* 
   * Initialize the VS interface. 
   */
   status_n = Vstart (file_id);

   /* 
   * Get the reference number of the vdata named VDATA_NAME.
   */
   vdata_ref = VSfind (file_id, VDATA_NAME);

   /*
   * Attach to the vdata for writing. 
   */
   vdata_id = VSattach (file_id, vdata_ref, "w");

   /*
   * Attach an attribute to the vdata, i.e., indicated by the second parameter.
   */
   status_n = VSsetattr (vdata_id, _HDF_VDATA, VATTR_NAME, DFNT_CHAR,
                                                   VATTR_N_VALUES, vd_attr);

   /*
   * Get the index of the field FIELD_NAME within the vdata.
   */
   status_n = VSfindex (vdata_id, FIELD_NAME, &field_index);

   /*
   * Attach an attribute to the field field_index.
   */
   status_n = VSsetattr (vdata_id, field_index, FATTR_NAME, DFNT_INT32, 
                                                   FATTR_N_VALUES, fld_attr);

   /*
   * Get the number of attributes attached to the vdata's first 
   * field - should be 0. 
   */
   n_fldattrs = VSfnattrs (vdata_id, 0);
   printf ( "Number of attributes of the first field of the vdata: %d\n", 
             n_fldattrs);

   /*
   * Get the number of attributes attached to the field specified by 
   * field_index - should be 1.
   */
   n_fldattrs = VSfnattrs (vdata_id, field_index);
   printf ( "Number of attributes of field %s: %d\n", FIELD_NAME, n_fldattrs);

   /*
   * Get the total number of the field's and vdata's attributes - should be 2. 
   */
   n_vdattrs = VSnattrs (vdata_id);
   printf ( "Number of attributes of the vdata and its fields: %d\n", 
             n_vdattrs);

   /*
   * Get information about the vdata's first attribute, indicated
   * by the third parameter which is the index of the attribute. 
   */
   status_n = VSattrinfo (vdata_id, _HDF_VDATA, 0, vattr_name, 
                          &vdata_type, &vdata_n_values, &vdata_size);

   /*
   * Get information about the first attribute of the field specified by 
   * field_index. 
   */
   status_n = VSattrinfo (vdata_id, field_index, 0, fattr_name, &field_type, 
                          &field_n_values, &field_size);

   /*
   * Get the vdata's first attribute. 
   */
   status_n = VSgetattr (vdata_id, _HDF_VDATA, 0, vattr_buf);
   printf("Values of the vdata attribute = %c %c %c\n", vattr_buf[0],
                          vattr_buf[1], vattr_buf[2]);

   /*
   * Get the first attribute of the field specified by field_index.
   */
   status_n = VSgetattr (vdata_id, field_index, 0, fattr_buf);
   printf("Values of the field attribute = %d %d %d %d\n", fattr_buf[0], 
                          fattr_buf[1], fattr_buf[2], fattr_buf[3]);

   /*
   * Terminate access to the vdata and to the VS interface, then close 
   * the HDF file. 
   */
   status_32 = VSdetach (vdata_id);
   status_n  = Vend (file_id);
   status_32 = Hclose (file_id);
   return 0;
}
示例#22
0
static void
test_undefined(void)
{
    int32 status;       /* Status values from routines */
    int32 file_id;          /* File ID */
    int32 vg1;          /* Vdata ID */
    int32 ref;          /* Vdata ref */
    intn is_internal;   /* to test Vgisinternal */
    uint16 name_len;	/* Length of a vgroup's name or class name */
    /* to simulate calls to Vgetclass/Vgetname in older applications */
    char vgname[VGNAMELENMAX+1], vgclass[VGNAMELENMAX+1];

    /* Open the HDF file. */
    file_id = Hopen(NONAMECLASS, DFACC_CREATE, 0);
    CHECK_VOID(file_id,FAIL,"Hopen");

    /* Initialize HDF for subsequent vgroup/vdata access. */
    status = Vstart(file_id);
    CHECK_VOID(status,FAIL,"Vstart");

    /* Create a vgroup which will have name set but not class */
    vg1 = Vattach(file_id, -1, "w");
    CHECK_VOID(vg1,FAIL,"VSattach");

    status=Vsetname(vg1, VG_LONGNAME);
    CHECK_VOID(status,FAIL,"VSsetname");

    status = Vdetach(vg1);
    CHECK_VOID(status,FAIL,"Vdetach");
    
    /* Create another vgroup which will have class but not name */
    vg1 = Vattach(file_id, -1, "w");
    CHECK_VOID(vg1,FAIL,"VSattach");

    status=Vsetclass(vg1, VG_LONGCLASS);
    CHECK_VOID(status,FAIL,"VSsetname");

    status = Vdetach(vg1);
    CHECK_VOID(status,FAIL,"Vdetach");
    
    status = Vend(file_id);
    CHECK_VOID(status,FAIL,"Vend");

    status = Hclose(file_id);
    CHECK_VOID(status,FAIL,"Hclose");

    /* Re-open the HDF file. */
    file_id = Hopen(NONAMECLASS, DFACC_RDWR, 0);
    CHECK_VOID(file_id,FAIL,"Hopen");

    /* Initialize HDF for subsequent vgroup/vdata access. */
    status = Vstart(file_id);
    CHECK_VOID(status,FAIL,"Vstart");

    /* Find the long name vgroup. */
    ref=Vfind(file_id,VG_LONGNAME);
    CHECK_VOID(ref,FAIL,"VSfind");

    vg1 = Vattach(file_id, ref, "r");
    CHECK_VOID(vg1,FAIL,"VSattach");

    /* Test Vgisinternal */
    is_internal = Vgisinternal(vg1);
    CHECK_VOID(is_internal, FAIL, "Vgisinternal");
    VERIFY_VOID(is_internal, FALSE, "Vgisinternal");
    
    /* Try getting the vgroup's class without calling first Vgetclassnamelen.
       This shows that bug HDFFR-1288 is fixed. */
    status=Vgetclass(vg1, vgclass);
    CHECK_VOID(status,FAIL,"Vgetclass");
    VERIFY_VOID(HDstrlen(vgclass), 0, "VSgetclass");

    /* The length of the class name should be 0 */
    status = Vgetclassnamelen(vg1, &name_len);
    CHECK_VOID(status,FAIL,"Vgetclassnamelen");
    VERIFY_VOID(name_len, 0, "VSgetclassnamelen");

    status = Vdetach(vg1);
    CHECK_VOID(status,FAIL,"Vdetach");
    
    /* Find the vgroup with class VG_LONGCLASS.  This vgroup doesn't have a name */
    ref=Vfindclass(file_id, VG_LONGCLASS);
    CHECK_VOID(ref,FAIL,"VSfindclass");

    vg1 = Vattach(file_id, ref, "r");
    CHECK_VOID(vg1,FAIL,"VSattach");

    /* Try getting the vgroup's name without calling first Vgetclassnamelen.
       Similar to class name in bug HDFFR-1288. */
    status=Vgetname(vg1, vgname);
    CHECK_VOID(status,FAIL,"Vgetname");
    VERIFY_VOID(HDstrlen(vgname), 0, "VSgetname");

    /* The length of the name should be 0 */
    status = Vgetnamelen(vg1, &name_len);
    CHECK_VOID(status,FAIL,"Vgetnamelen");
    VERIFY_VOID(name_len, 0, "VSgetnamelen");

    status = Vdetach(vg1);
    CHECK_VOID(status,FAIL,"Vdetach");
    
    status = Vend(file_id);
    CHECK_VOID(status,FAIL,"Vend");

    status = Hclose(file_id);
    CHECK_VOID(status,FAIL,"Hclose");

} /* test_undefined() */
示例#23
0
static void
test_vglongnames(void)
{
    int32 file_id;      /* File ID */
    int32 vg1;          /* Vdata ID */
    int32 ref;          /* Vdata ref */
    uint16 name_len;	/* Length of a vgroup's name or class name */
    char *vgname, *vgclass;
    intn is_internal;
    int32 status;       /* Status values from routines */

    /* Open the HDF file. */
    file_id = Hopen(LONGNAMES, DFACC_CREATE, 0);
    CHECK_VOID(file_id,FAIL,"Hopen");

    /* Initialize HDF for subsequent vgroup/vdata access. */
    status = Vstart(file_id);
    CHECK_VOID(status,FAIL,"Vstart");

    /* Create a new vgroup. */
    vg1 = Vattach(file_id, -1, "w");
    CHECK_VOID(vg1,FAIL,"VSattach");

    status=Vsetname(vg1, VG_LONGNAME);
    CHECK_VOID(status,FAIL,"VSsetname");

    status=Vsetclass(vg1, VG_LONGCLASS);
    CHECK_VOID(status,FAIL,"VSsetname");

    status = Vdetach(vg1);
    CHECK_VOID(status,FAIL,"Vdetach");
    
    /* Create another vgroup of the same class. */
    vg1 = Vattach(file_id, -1, "w");
    CHECK_VOID(vg1,FAIL,"VSattach");

    status=Vsetname(vg1, VGROUP1);
    CHECK_VOID(status,FAIL,"VSsetname");

    status=Vsetclass(vg1, VG_LONGCLASS);
    CHECK_VOID(status,FAIL,"VSsetname");

    status = Vdetach(vg1);
    CHECK_VOID(status,FAIL,"Vdetach");
    
    status = Vend(file_id);
    CHECK_VOID(status,FAIL,"Vend");

    status = Hclose(file_id);
    CHECK_VOID(status,FAIL,"Hclose");

    /* Re-open the HDF file. */
    file_id = Hopen(LONGNAMES, DFACC_RDWR, 0);
    CHECK_VOID(file_id,FAIL,"Hopen");

    /* Initialize HDF for subsequent vgroup/vdata access. */
    status = Vstart(file_id);
    CHECK_VOID(status,FAIL,"Vstart");

    /* Find the long name vgroup. */
    ref=Vfind(file_id,VG_LONGNAME);
    CHECK_VOID(ref,FAIL,"VSfind");

    vg1 = Vattach(file_id, ref, "r");
    CHECK_VOID(vg1,FAIL,"VSattach");

    /* Test Vgisinternal */
    is_internal = Vgisinternal(vg1);
    CHECK_VOID(is_internal, FAIL, "Vgisinternal");
    VERIFY_VOID(is_internal, FALSE, "Vgisinternal");
    
    /* get the vgroup's name */
    status = Vgetnamelen(vg1, &name_len);
    CHECK_VOID(status,FAIL,"Vgetnamelen");

    vgname = (char *) HDmalloc(sizeof(char *) * (name_len+1));
    CHECK_ALLOC(vgname, "vgname", "test_vglongnames" );

    status=Vgetname(vg1, vgname);
    CHECK_VOID(status,FAIL,"VSgetname");
    VERIFY_CHAR_VOID(vgname, VG_LONGNAME, "Vgetname");

    if (vgname != NULL)
        HDfree(vgname);

    /* get the vgroup's class */
    status = Vgetclassnamelen(vg1, &name_len);
    CHECK_VOID(status,FAIL,"Vgetnamelen");

    vgclass = (char *) HDmalloc(sizeof(char *) * (name_len+1));
    CHECK_ALLOC(vgclass, "vgclass", "test_vglongnames" );

    status=Vgetclass(vg1, vgclass);
    CHECK_VOID(status,FAIL,"VSgetclass");
    VERIFY_CHAR_VOID(vgclass, VG_LONGCLASS, "Vgetclass");

    if (vgclass != NULL)
        HDfree(vgclass);

    status = Vdetach(vg1);
    CHECK_VOID(status,FAIL,"Vdetach");
    
    /* Find the vgroup VGROUP1. */
    ref=Vfind(file_id,VGROUP1);
    CHECK_VOID(ref,FAIL,"VSfind");

    vg1 = Vattach(file_id, ref, "r");
    CHECK_VOID(vg1,FAIL,"VSattach");

    /* get the vgroup's name */
    status = Vgetnamelen(vg1, &name_len);
    CHECK_VOID(status,FAIL,"Vgetnamelen");

    vgname = (char *) HDmalloc(sizeof(char *) * (name_len+1));
    CHECK_ALLOC(vgname, "vgname", "test_vglongnames" );

    status=Vgetname(vg1, vgname);
    CHECK_VOID(status,FAIL,"VSgetname");

    if (HDstrcmp(vgname, VGROUP1)) {
        num_errs++;
        printf(">>> Got bogus Vgroup name : %s\n", vgname);
    }

    if (vgname != NULL)
        HDfree(vgname);

    /* get the vgroup's class */
    status = Vgetclassnamelen(vg1, &name_len);
    CHECK_VOID(status,FAIL,"Vgetnamelen");

    vgclass = (char *) HDmalloc(sizeof(char *) * (name_len+1));
    CHECK_ALLOC(vgclass, "vgclass", "test_vglongnames" );

    status=Vgetclass(vg1, vgclass);
    CHECK_VOID(status,FAIL,"VSgetclass");

    if (HDstrcmp(vgclass, VG_LONGCLASS)) {
        num_errs++;
        printf(">>> Got bogus Vgroup class : %s\n", vgclass);
    }

    if (vgclass != NULL)
        HDfree(vgclass);

    status = Vdetach(vg1);
    CHECK_VOID(status,FAIL,"Vdetach");
    
    status = Vend(file_id);
    CHECK_VOID(status,FAIL,"Vend");

    status = Hclose(file_id);
    CHECK_VOID(status,FAIL,"Hclose");

} /* test_vglongnames() */
示例#24
0
GDALDataset *HDF4Dataset::Open( GDALOpenInfo * poOpenInfo )

{
    int32	i;

    if( !Identify( poOpenInfo ) )
        return NULL;

/* -------------------------------------------------------------------- */
/*      Try opening the dataset.                                        */
/* -------------------------------------------------------------------- */
    int32	hHDF4;
    
    hHDF4 = Hopen(poOpenInfo->pszFilename, DFACC_READ, 0);
    
    if( hHDF4 <= 0 )
        return( NULL );

    Hclose( hHDF4 );

/* -------------------------------------------------------------------- */
/*      Create a corresponding GDALDataset.                             */
/* -------------------------------------------------------------------- */
    HDF4Dataset *poDS;

    poDS = new HDF4Dataset();

    poDS->fp = poOpenInfo->fp;
    poOpenInfo->fp = NULL;
    
/* -------------------------------------------------------------------- */
/*          Open HDF SDS Interface.                                     */
/* -------------------------------------------------------------------- */
    poDS->hSD = SDstart( poOpenInfo->pszFilename, DFACC_READ );

    if ( poDS->hSD == -1 )
    {
	delete poDS;
        return NULL;
    }
   
/* -------------------------------------------------------------------- */
/*		Now read Global Attributes.				*/
/* -------------------------------------------------------------------- */
    if ( poDS->ReadGlobalAttributes( poDS->hSD ) != CE_None )
    {
	delete poDS;
        return NULL;
    }

    poDS->SetMetadata( poDS->papszGlobalMetadata, "" );

/* -------------------------------------------------------------------- */
/*		Determine type of file we read.				*/
/* -------------------------------------------------------------------- */
    const char	*pszValue;
    
    if ( (pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata,
                                       "Signature"))
	 && EQUAL( pszValue, pszGDALSignature ) )
    {
	poDS->iSubdatasetType = H4ST_GDAL;
	poDS->pszSubdatasetType = "GDAL_HDF4";
    }

    else if ( (pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata, "Title"))
	 && EQUAL( pszValue, "SeaWiFS Level-1A Data" ) )
    {
	poDS->iSubdatasetType = H4ST_SEAWIFS_L1A;
	poDS->pszSubdatasetType = "SEAWIFS_L1A";
    }

    else if ( (pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata, "Title"))
	&& EQUAL( pszValue, "SeaWiFS Level-2 Data" ) )
    {
	poDS->iSubdatasetType = H4ST_SEAWIFS_L2;
	poDS->pszSubdatasetType = "SEAWIFS_L2";
    }

    else if ( (pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata, "Title"))
	&& EQUAL( pszValue, "SeaWiFS Level-3 Standard Mapped Image" ) )
    {
	poDS->iSubdatasetType = H4ST_SEAWIFS_L3;
	poDS->pszSubdatasetType = "SEAWIFS_L3";
    }

    else if ( (pszValue = CSLFetchNameValue(poDS->papszGlobalMetadata,
                                            "L1 File Generated By"))
	&& EQUALN( pszValue, "HYP version ", 12 ) )
    {
	poDS->iSubdatasetType = H4ST_HYPERION_L1;
	poDS->pszSubdatasetType = "HYPERION_L1";
    }

    else
    {
	poDS->iSubdatasetType = H4ST_UNKNOWN;
	poDS->pszSubdatasetType = "UNKNOWN";
    }

/* -------------------------------------------------------------------- */
/*  If we have HDF-EOS dataset, process it here.	                */
/* -------------------------------------------------------------------- */
    char	szName[VSNAMELENMAX + 1], szTemp[8192];
    char	*pszString;
    const char  *pszName;
    int		nCount;
    int32	aiDimSizes[H4_MAX_VAR_DIMS];
    int32	iRank, iNumType, nAttrs;
    bool        bIsHDF = true;
    
    // Sometimes "HDFEOSVersion" attribute is not defined and we will
    // determine HDF-EOS datasets using other records
    // (see ReadGlobalAttributes() method).
    if ( poDS->bIsHDFEOS
         || CSLFetchNameValue(poDS->papszGlobalMetadata, "HDFEOSVersion") )
    {
        bIsHDF  = false;

        int32   nSubDatasets, nStrBufSize;

/* -------------------------------------------------------------------- */
/*  Process swath layers.                                               */
/* -------------------------------------------------------------------- */
        hHDF4 = SWopen( poOpenInfo->pszFilename, DFACC_READ );
        if( hHDF4 < 0)
        {
            delete poDS;
            CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open HDF4 `%s'.\n", poOpenInfo->pszFilename );
            return NULL;
        } 
        nSubDatasets = SWinqswath(poOpenInfo->pszFilename, NULL, &nStrBufSize);
#if DEBUG
        CPLDebug( "HDF4", "Number of HDF-EOS swaths: %d", (int)nSubDatasets );
#endif
        if ( nSubDatasets > 0 && nStrBufSize > 0 )
        {
            char    *pszSwathList;
            char    **papszSwaths;

            pszSwathList = (char *)CPLMalloc( nStrBufSize + 1 );
            SWinqswath( poOpenInfo->pszFilename, pszSwathList, &nStrBufSize );
            pszSwathList[nStrBufSize] = '\0';

#if DEBUG
            CPLDebug( "HDF4", "List of HDF-EOS swaths: %s", pszSwathList );
#endif

            papszSwaths =
                CSLTokenizeString2( pszSwathList, ",", CSLT_HONOURSTRINGS );
            CPLFree( pszSwathList );

            if ( nSubDatasets != CSLCount(papszSwaths) )
            {
                CSLDestroy( papszSwaths );
                delete poDS;
                CPLDebug( "HDF4", "Can not parse list of HDF-EOS grids." );
                return NULL;
            }

            for ( i = 0; i < nSubDatasets; i++)
            {
                char    *pszFieldList;
                char    **papszFields;
                int32   *paiRank, *paiNumType;
                int32   hSW, nFields, j;

                hSW = SWattach( hHDF4, papszSwaths[i] );

                nFields = SWnentries( hSW, HDFE_NENTDFLD, &nStrBufSize );
                pszFieldList = (char *)CPLMalloc( nStrBufSize + 1 );
                paiRank = (int32 *)CPLMalloc( nFields * sizeof(int32) );
                paiNumType = (int32 *)CPLMalloc( nFields * sizeof(int32) );

                SWinqdatafields( hSW, pszFieldList, paiRank, paiNumType );

#if DEBUG
                {
                    char *pszTmp =
                        SPrintArray( GDT_UInt32, paiRank, nFields, "," );

                    CPLDebug( "HDF4", "Number of data fields in swath %d: %d",
                              (int) i, (int) nFields );
                    CPLDebug( "HDF4", "List of data fields in swath %d: %s",
                              (int) i, pszFieldList );
                    CPLDebug( "HDF4", "Data fields ranks: %s", pszTmp );

                    CPLFree( pszTmp );
                }
#endif

                papszFields = CSLTokenizeString2( pszFieldList, ",",
                                                  CSLT_HONOURSTRINGS );
                
                for ( j = 0; j < nFields; j++ )
                {
                    SWfieldinfo( hSW, papszFields[j], &iRank, aiDimSizes,
                                 &iNumType, NULL );

                    if ( iRank < 2 )
                        continue;

	            // Add field to the list of GDAL subdatasets
                    nCount = CSLCount( poDS->papszSubDatasets ) / 2;
                    sprintf( szTemp, "SUBDATASET_%d_NAME", nCount + 1 );
	            // We will use the field index as an identificator.
                    poDS->papszSubDatasets =
                        CSLSetNameValue( poDS->papszSubDatasets, szTemp,
                                CPLSPrintf("HDF4_EOS:EOS_SWATH:\"%s\":%s:%s",
                                           poOpenInfo->pszFilename,
                                           papszSwaths[i], papszFields[j]) );

                    sprintf( szTemp, "SUBDATASET_%d_DESC", nCount + 1 );
                    pszString = SPrintArray( GDT_UInt32, aiDimSizes,
                                             iRank, "x" );
                    poDS->papszSubDatasets =
                        CSLSetNameValue( poDS->papszSubDatasets, szTemp,
                                         CPLSPrintf( "[%s] %s %s (%s)", pszString,
                                         papszFields[j],
                                         papszSwaths[i],
                                         poDS->GetDataTypeName(iNumType) ) );
                    CPLFree( pszString );
                }

                CSLDestroy( papszFields );
                CPLFree( paiNumType );
                CPLFree( paiRank );
                CPLFree( pszFieldList );
                SWdetach( hSW );
            }

            CSLDestroy( papszSwaths );
        }
        SWclose( hHDF4 );

/* -------------------------------------------------------------------- */
/*  Process grid layers.                                                */
/* -------------------------------------------------------------------- */
        hHDF4 = GDopen( poOpenInfo->pszFilename, DFACC_READ );
        nSubDatasets = GDinqgrid( poOpenInfo->pszFilename, NULL, &nStrBufSize );
#if DEBUG
        CPLDebug( "HDF4", "Number of HDF-EOS grids: %d", (int)nSubDatasets );
#endif
        if ( nSubDatasets > 0 && nStrBufSize > 0 )
        {
            char    *pszGridList;
            char    **papszGrids;

            pszGridList = (char *)CPLMalloc( nStrBufSize + 1 );
            GDinqgrid( poOpenInfo->pszFilename, pszGridList, &nStrBufSize );

#if DEBUG
            CPLDebug( "HDF4", "List of HDF-EOS grids: %s", pszGridList );
#endif

            papszGrids =
                CSLTokenizeString2( pszGridList, ",", CSLT_HONOURSTRINGS );
            CPLFree( pszGridList );

            if ( nSubDatasets != CSLCount(papszGrids) )
            {
                CSLDestroy( papszGrids );
                delete poDS;
                CPLDebug( "HDF4", "Can not parse list of HDF-EOS grids." );
                return NULL;
            }

            for ( i = 0; i < nSubDatasets; i++)
            {
                char    *pszFieldList;
                char    **papszFields;
                int32   *paiRank, *paiNumType;
                int32   hGD, nFields, j;

                hGD = GDattach( hHDF4, papszGrids[i] );

                nFields = GDnentries( hGD, HDFE_NENTDFLD, &nStrBufSize );
                pszFieldList = (char *)CPLMalloc( nStrBufSize + 1 );
                paiRank = (int32 *)CPLMalloc( nFields * sizeof(int32) );
                paiNumType = (int32 *)CPLMalloc( nFields * sizeof(int32) );

                GDinqfields( hGD, pszFieldList, paiRank, paiNumType );

#if DEBUG
                {
                    char* pszTmp =
                            SPrintArray( GDT_UInt32, paiRank, nFields, "," );
                    CPLDebug( "HDF4", "Number of fields in grid %d: %d",
                            (int) i, (int) nFields );
                    CPLDebug( "HDF4", "List of fields in grid %d: %s",
                            (int) i, pszFieldList );
                    CPLDebug( "HDF4", "Fields ranks: %s",
                            pszTmp );
                    CPLFree( pszTmp );
                }
#endif

                papszFields = CSLTokenizeString2( pszFieldList, ",",
                                                  CSLT_HONOURSTRINGS );
                
                for ( j = 0; j < nFields; j++ )
                {
                    GDfieldinfo( hGD, papszFields[j], &iRank, aiDimSizes,
                                 &iNumType, NULL );

                    if ( iRank < 2 )
                        continue;

	            // Add field to the list of GDAL subdatasets
                    nCount = CSLCount( poDS->papszSubDatasets ) / 2;
                    sprintf( szTemp, "SUBDATASET_%d_NAME", nCount + 1 );
	            // We will use the field index as an identificator.
                    poDS->papszSubDatasets =
                        CSLSetNameValue(poDS->papszSubDatasets, szTemp,
                                CPLSPrintf( "HDF4_EOS:EOS_GRID:\"%s\":%s:%s",
                                            poOpenInfo->pszFilename,
                                            papszGrids[i], papszFields[j]));

                    sprintf( szTemp, "SUBDATASET_%d_DESC", nCount + 1 );
                    pszString = SPrintArray( GDT_UInt32, aiDimSizes,
                                             iRank, "x" );
                    poDS->papszSubDatasets =
                        CSLSetNameValue( poDS->papszSubDatasets, szTemp,
                                         CPLSPrintf("[%s] %s %s (%s)", pszString,
                                             papszFields[j],
                                             papszGrids[i],
                                             poDS->GetDataTypeName(iNumType)) );
                    CPLFree( pszString );
                }

                CSLDestroy( papszFields );
                CPLFree( paiNumType );
                CPLFree( paiRank );
                CPLFree( pszFieldList );
                GDdetach( hGD );
            }

            CSLDestroy( papszGrids );
            GDclose( hHDF4 );
        }
        GDclose( hHDF4 );

        bIsHDF = ( nSubDatasets == 0 ); // Try to read as HDF
    }

    if( bIsHDF )
    {

/* -------------------------------------------------------------------- */
/*  Make a list of subdatasets from SDSs contained in input HDF file.	*/
/* -------------------------------------------------------------------- */
        int32   nDatasets;

        if ( SDfileinfo( poDS->hSD, &nDatasets, &nAttrs ) != 0 )
	    return NULL;

        for ( i = 0; i < nDatasets; i++ )
        {
            int32	iSDS;

            iSDS = SDselect( poDS->hSD, i );
            if ( SDgetinfo( iSDS, szName, &iRank, aiDimSizes, &iNumType, &nAttrs) != 0 )
                return NULL;
            
            if ( iRank == 1 )		// Skip 1D datsets
                    continue;

            // Do sort of known datasets. We will display only image bands
            if ( (poDS->iSubdatasetType == H4ST_SEAWIFS_L1A ) &&
                      !EQUALN( szName, "l1a_data", 8 ) )
                    continue;
            else
                pszName = szName;
            
            // Add datasets with multiple dimensions to the list of GDAL subdatasets
            nCount = CSLCount( poDS->papszSubDatasets ) / 2;
            sprintf( szTemp, "SUBDATASET_%d_NAME", nCount + 1 );
            // We will use SDS index as an identificator, because SDS names
            // are not unique. Filename also needed for further file opening
            poDS->papszSubDatasets = CSLSetNameValue(poDS->papszSubDatasets, szTemp, 
                  CPLSPrintf( "HDF4_SDS:%s:\"%s\":%ld", poDS->pszSubdatasetType,
                              poOpenInfo->pszFilename, (long)i) );
            sprintf( szTemp, "SUBDATASET_%d_DESC", nCount + 1 );
            pszString = SPrintArray( GDT_UInt32, aiDimSizes, iRank, "x" );
            poDS->papszSubDatasets = CSLSetNameValue(poDS->papszSubDatasets, szTemp,
                CPLSPrintf( "[%s] %s (%s)", pszString,
                            pszName, poDS->GetDataTypeName(iNumType)) );
            CPLFree( pszString );

            SDendaccess( iSDS );
        }

        SDend( poDS->hSD );
        poDS->hSD = 0;
    }

/* -------------------------------------------------------------------- */
/*      Build a list of raster images. Note, that HDF-EOS dataset may   */
/*      contain a raster image as well.                                 */
/* -------------------------------------------------------------------- */
    hHDF4 = Hopen(poOpenInfo->pszFilename, DFACC_READ, 0);
    poDS->hGR = GRstart( hHDF4 );

    if ( poDS->hGR != -1 )
    {
        if ( GRfileinfo( poDS->hGR, &poDS->nImages, &nAttrs ) == -1 )
            return NULL;
        
        for ( i = 0; i < poDS->nImages; i++ )
        {
            int32   iInterlaceMode; 
            int32   iGR = GRselect( poDS->hGR, i );

            // iRank in GR interface has another meaning. It represents number
            // of samples per pixel. aiDimSizes has only two dimensions.
            if ( GRgetiminfo( iGR, szName, &iRank, &iNumType, &iInterlaceMode,
                              aiDimSizes, &nAttrs ) != 0 )
                return NULL;
            nCount = CSLCount( poDS->papszSubDatasets ) / 2;
            sprintf( szTemp, "SUBDATASET_%d_NAME", nCount + 1 );
            poDS->papszSubDatasets = CSLSetNameValue(poDS->papszSubDatasets,
                szTemp,CPLSPrintf( "HDF4_GR:UNKNOWN:\"%s\":%ld",
                                   poOpenInfo->pszFilename, (long)i));
            sprintf( szTemp, "SUBDATASET_%d_DESC", nCount + 1 );
            pszString = SPrintArray( GDT_UInt32, aiDimSizes, 2, "x" );
            poDS->papszSubDatasets = CSLSetNameValue(poDS->papszSubDatasets,
                szTemp, CPLSPrintf( "[%sx%ld] %s (%s)", pszString, (long)iRank,
                                    szName, poDS->GetDataTypeName(iNumType)) );
            CPLFree( pszString );

            GRendaccess( iGR );
        }

        GRend( poDS->hGR );
        poDS->hGR = 0;
    }

    Hclose( hHDF4 );

    poDS->nRasterXSize = poDS->nRasterYSize = 512; // XXX: bogus values

    // Make sure we don't try to do any pam stuff with this dataset.
    poDS->nPamFlags |= GPF_NOSAVE;

/* -------------------------------------------------------------------- */
/*      If we have single subdataset only, open it immediately          */
/* -------------------------------------------------------------------- */
    if ( CSLCount( poDS->papszSubDatasets ) / 2 == 1 )
    {
        char *pszSDSName;
        pszSDSName = CPLStrdup( CSLFetchNameValue( poDS->papszSubDatasets,
                            "SUBDATASET_1_NAME" ));
        delete poDS;
        poDS = NULL;

        GDALDataset* poRetDS = (GDALDataset*) GDALOpen( pszSDSName, poOpenInfo->eAccess );
        CPLFree( pszSDSName );

        if (poRetDS)
        {
            poRetDS->SetDescription(poOpenInfo->pszFilename);
        }

        return poRetDS;
    }
    else
    {
/* -------------------------------------------------------------------- */
/*      Confirm the requested access is supported.                      */
/* -------------------------------------------------------------------- */
        if( poOpenInfo->eAccess == GA_Update )
        {
            delete poDS;
            CPLError( CE_Failure, CPLE_NotSupported, 
                      "The HDF4 driver does not support update access to existing"
                      " datasets.\n" );
            return NULL;
        }
    
    }

    return( poDS );
}
示例#25
0
    int32       fid, fid1;
    int32       aid1, aid2;
    int32       fileid, length, offset, posn;
    uint16      tag, ref;
    int16       acc_mode, special;
    int32       ret;
    int         i;
    intn        errors = 0;
    intn        ret_bool;

    for (i = 0; i < BUF_SIZE; i++)
        outbuf[i] = (char) (i % 256);

    MESSAGE(5, printf("Creating a file %s\n", TESTFILE_NAME);
        );
    fid = Hopen(TESTFILE_NAME, DFACC_CREATE, 0);
    CHECK_VOID(fid, FAIL, "Hopen");

    ret_bool = (intn) Hishdf(TESTFILE_NAME);
    CHECK_VOID(ret_bool, FALSE, "Hishdf");

    ret = (int32)Hnewref(fid);
    CHECK_VOID(ret, FAIL, "Hnewref");

    MESSAGE(5, printf("Reading / Writing to file\n");
        );
    ret = Hputelement(fid, (uint16) 100, 1,
                  (const uint8 *) "testing 100 1", (int32)HDstrlen("testing 100 1") + 1);
    CHECK_VOID(ret, FAIL, "Hputelement");

    ret = Hputelement(fid, (uint16) 100, (uint16) 4, outbuf, 2000);