结合C++和GDAL实现shapefile(shp)文件的读取

时间:2022-08-12 16:39:07

工具:vs2012+GDAL 2.0

数据:中国省界SHP文件bou2_4p.shp   可点击下载

包含头文件:

#include "ogrsf_frmts.h"

代码:

int main()
{
GDALAllRegister();
GDALDataset *poDS;
CPLSetConfigOption("SHAPE_ENCODING",""); //解决中文乱码问题
//读取shp文件
poDS = (GDALDataset*) GDALOpenEx("d:/shapefile/bou2_4p.shp", GDAL_OF_VECTOR, NULL, NULL, NULL ); if( poDS == NULL )
{
printf( "Open failed.\n%s" );
return 0;
} OGRLayer *poLayer;
poLayer = poDS->GetLayer(); //读取层
OGRFeature *poFeature; poLayer->ResetReading();
int i=;
while( (poFeature = poLayer->GetNextFeature()) != NULL )
{
if(poFeature->GetFieldAsDouble("AREA")<) continue; //去掉面积过小的polygon
i=i++;
cout<<i<<" ";
OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn();
int iField;
int n=poFDefn->GetFieldCount(); //获得字段的数目,不包括前两个字段(FID,Shape);
for( iField = ; iField <n; iField++ )
{
//输出每个字段的值
cout<<poFeature->GetFieldAsString(iField)<<" ";
}
cout<<endl;
OGRFeature::DestroyFeature( poFeature );
}
GDALClose( poDS );
system("pause");
return ;
}

结果显示:

结合C++和GDAL实现shapefile(shp)文件的读取