工具:vs2012+GDAL 2.0
包含头文件:
#include "ogrsf_frmts.h"
int main() { const char *pszDriverName = "ESRI Shapefile"; GDALDriver *poDriver; GDALAllRegister(); poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName ); if( poDriver == NULL ) { printf( "%s driver not available.\n", pszDriverName ); return 0; } GDALDataset *poDS; poDS = poDriver->Create("d:/newShp.shp", 0, 0, 0, GDT_Unknown, NULL ); //创建shp文件 if( poDS == NULL ) { printf( "Creation of output file failed.\n" ); return 0; } OGRLayer *poLayer; poLayer = poDS->CreateLayer( "point_out", NULL, wkbPoint, NULL ); if( poLayer == NULL ) { printf( "Layer creation failed.\n" ); return 0; } OGRFieldDefn idField("ID",OFTReal); OGRFieldDefn firstField("NAME",OFTInteger); OGRFieldDefn secondField("X",OFTReal); OGRFieldDefn thirdField("Y",OFTReal); idField.SetWidth(32); firstField.SetWidth(32); secondField.SetWidth(32); thirdField.SetWidth(32); poLayer->CreateField(&idField); poLayer->CreateField(&firstField); poLayer->CreateField(&secondField); poLayer->CreateField(&thirdField); int x, y; int a=10,b=100; for(int i=1;i<=10;i++) { OGRFeature *poFeature; poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() ); poFeature->SetField("ID",i); poFeature->SetField("NAME",i); x=(rand() % (b-a))+ a; y=(rand() % (b-a))+ a; poFeature->SetField("X",x); poFeature->SetField("Y",y); OGRPoint pt; pt.setX( x ); pt.setY( y ); poFeature->SetGeometry( &pt ); if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE ) { printf( "Failed to create feature in shapefile.\n" ); return 0; } OGRFeature::DestroyFeature( poFeature ); } GDALClose( poDS ); return 1;}
这样,就会在d盘根目录生成一个newShp.shp的文件,用arcgis打开,显示如下
时间: 2024-10-12 14:00:02