Example 1: Time as Attribute

In this example, we will work with the following site list:
name|time
desc|Example of using time as an attribute
time|Mon Apr 17 14:24:06 EST 1995
10.8|0|9.8|Fri Sep 13 10:00:00 1986 %31.4
11|5.5|9.9|Fri Sep 14 00:20:00 1985 %36.4
5.1|3.9|10|Fri Sep 15 00:00:30 1984 %28.4
This data has three dimensions (assume easting, northing, and elevation), five string attributes, and one decimal attributes.

Now follow along in this skeleton C program. Remember that in real code, you should always check return values.

#include "site.h"           /* include definitions and prototypes */
#include "gis.h"            /* includes stdio.h for file I/O */
int main (argc, argv)
  char **argv;
  int argc;
{
  int dims=0,cat=0,strs=0,dbls=0;
  Site *mysite;               /* pointer to Site */
  Site_head info;             
  FILE *fp;                   

  /* find mapset that site list is in and open the site list */
  mapset = G_find_file ("site_lists", parm.input->answer, "");

  fp = G_fopen_sites_old (parm.input->answer, mapset);

  /* G_site_describe should be called immediately after the
   * file is opened or at least before any seeks are done
   * on the file.
   */
  if (G_site_describe (fp, &dims, &cat, &strs, &dbls)!=0)
    G_fatal_error("failed to guess format");

  fprintf(stdout,"Guessed %d %d %d %d (should be 3 5 1 0)\n",
          dims, strs, dbls,cat);

  /* 
  * Read header fields first, then write to stderr.
  * This step is optional since the first call to G_site_get()
  * would skip over any comment or header records. 
  */
  G_site_get_hdr(fp,&info);
  G_site_put_hdr(stderr,info);

  /* 
  * Allocate enough memory, according to the output 
  * of G_site_describe() 
  */
  mysite = G_site_new_struct (dims, strs, dbls);
  
  /* 
   * G_site_get() returns -1 on EOF, -2 on error. This code ignores
   * all records following the first invalid one.
   */
  while ((err=G_site_get (fp, mysite)) == 0) 
  {
    /* do something useful with time information */
  
    /* write the site to stderr instead of output file */
    G_site_put(stderr,mysite,cat);
  }
  
Running our sample program, we get:
Mapset <PERMANENT> in Location <temporal>
GRASS 4.1 > s.egtime time-h
name|time
desc|Example of using time as an attribute
time|Mon Apr 17 14:24:06 EST 1995
10.8|0|9.8|%31.4 @Fri @Sep @13 @10:00:00 @1986 
11|5.5|9.9|%36.4 @Fri @Sep @14 @00:20:00 @1985 
5.1|3.9|10|%28.4 @Fri @Sep @15 @00:00:30 @1984 
Compare the above output to the input site list given earlier.

In this example, we read "time" as five string attributes. Using the GRASS DateTime library, we could convert this to GRASS DateTimes and do sometime more useful with this information. We also could have used the TimeStamp GISlib functions to format a single standard GRASS TimeStamp string instead of requiring 5 separate strings.

Key Points

After studying the above, you should:
Darrell McCauley (mccauley@ecn.purdue.edu)
Last modified on