fun with Shapelib

We have some existing C modules which do a bunch of data processing, and wanted the ability to spit out shapefiles on demand.  Shapelib is a C library which allows for reading and writing shapefiles and dbf files.  Thanks to the API docs, here’s a pared down version of how to write a new point shapefile (with, in this case, one record):

#include <stdio.h>
#include <stdlib.h>
#include <libshp/shapefil.h>
/*
 build with: gcc -O -Wall -ansi -pedantic -g -L/usr/local/lib -lshp foo.c
*/
int main() {
    int i = 0;
    double *x;
    double *y;

    SHPHandle  hSHP;
    SHPObject *oSHP;
    DBFHandle  hDBF;

    x = malloc(sizeof(*x));
    y = malloc(sizeof(*y));

    /* create shapefile and dbf */
    hSHP = SHPCreate("bar", SHPT_POINT);
    hDBF = DBFCreate("bar");

    DBFAddField(hDBF, "stationid", FTString, 25, 0);

    /* add record */
    x[0] = -75;
    y[0] = 45;
    oSHP = SHPCreateSimpleObject(SHPT_POINT, 1, x, y, NULL);
    SHPWriteObject(hSHP, -1, oSHP);
    DBFWriteStringAttribute(hDBF, 0, 0, "abcdef");

    /* destroy */
    SHPDestroyObject(oSHP);

    /* close shapefile and dbf */
    SHPClose(hSHP);
    DBFClose(hDBF);
    free(x);
    free(y);

    return 0;
}

Done!

3 Comments so far »

  1. Durga said,

    Wrote on June 18, 2009 @ 06:08:34

    Internet Explorer 6.0 Windows XP

    That was short and sweet.Please add snippets for creating Line and Polygon shapefiles too.

    Posted from United States United States
    Internet Explorer 6.0 Windows XP
  2. tomkralidis said,

    Wrote on June 18, 2009 @ 20:59:20

    Mozilla Firefox 3.0.11 Mac OS X 10

    For lines and polygons, you would modify the SHPCreateSimpleObject function by setting the geometry type, number of vertices, and the vertices arrays accordingly.

    Posted from Canada Canada
    Mozilla Firefox 3.0.11 Mac OS X 10
  3. Sling Blade said,

    Wrote on July 27, 2009 @ 17:04:13

    Mozilla Firefox 3.5.1 Windows XP

    Awesome! Thanks for the demo, very helpful.

    Any ideas on converting Arcs to shape files using shapelib?

    Posted from New Zealand New Zealand
    Mozilla Firefox 3.5.1 Windows XP

Comment RSS · TrackBack URI

Leave a Comment

Name: (Required)

E-mail: (Required)

Website:

Comment:

Modified: 24 March 2009 07:03:48 EST