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!
