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!
Durga said,
Wrote on June 18, 2009 @ 06:08:34
That was short and sweet.Please add snippets for creating Line and Polygon shapefiles too.
Posted from United StatesInternet Explorer 6.0 Windows XP
tomkralidis said,
Wrote on June 18, 2009 @ 20:59:20
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 CanadaMozilla Firefox 3.0.11 Mac OS X 10
Sling Blade said,
Wrote on July 27, 2009 @ 17:04:13
Awesome! Thanks for the demo, very helpful.
Any ideas on converting Arcs to shape files using shapelib?
Posted from New ZealandMozilla Firefox 3.5.1 Windows XP