Skip to content

Instantly share code, notes, and snippets.

@malted
Created October 24, 2022 19:42
Show Gist options
  • Save malted/a3a6a71b42766118253ad1dd925032cf to your computer and use it in GitHub Desktop.
Save malted/a3a6a71b42766118253ad1dd925032cf to your computer and use it in GitHub Desktop.
Shapefile header analyser
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
unsigned char headerBuffer[100];
FILE *ptr;
ptr = fopen(argv[1], "rb");
fread(headerBuffer, sizeof(headerBuffer), 1, ptr);
int fileCode =
(headerBuffer[0] << 24) +
(headerBuffer[1] << 16) +
(headerBuffer[2] << 8) +
headerBuffer[3];
int shpFileCode = 0x0000270a;
if (fileCode == shpFileCode) {
printf("Analysing shapefile\n");
} else {
fprintf(stderr, "Error: file is not a shapefile. Exiting.");
return 1;
}
int length =
((headerBuffer[24] << 24) +
(headerBuffer[25] << 16) +
(headerBuffer[26] << 8) +
headerBuffer[27])
<< 1; // length is in 16 bit words; * 2 to get 8 bit bytes.
printf("File length: %d bytes\n", length);
int version =
headerBuffer[28] +
(headerBuffer[29] << 8) +
(headerBuffer[30] << 16) +
(headerBuffer[31] << 24);
printf("Shapefile version: %d\n", version);
int shapeType =
headerBuffer[32] +
(headerBuffer[33] << 8) +
(headerBuffer[34] << 16) +
(headerBuffer[35] << 24);
printf("Shape type: ");
switch (shapeType) {
case 0: printf("Null shape"); break;
case 1: printf("Point"); break;
case 3: printf("Polyline"); break;
case 5: printf("Polygon"); break;
case 8: printf("MultiPoint"); break;
case 11: printf("PointZ"); break;
case 13: printf("PolylineZ"); break;
case 15: printf("PolygonZ"); break;
case 18: printf("MultiPointZ"); break;
case 21: printf("PointM"); break;
case 23: printf("PolylineM"); break;
case 25: printf("PolygonM"); break;
case 28: printf("MultiPointM"); break;
case 31: printf("MultiPatch"); break;
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment