#include "ogrsf_frmts.h"
int main()
{
const char *pszDriverName = "ESRI Shapefile";
GDALDriver *poDriver;
GDALAllRegister(); //注册所有驱动
poDriver = GetGDALDriverManager->GetDriverByName( pszDriverName ); //获取创建输出文件所需要的Shapefile driver
if( poDriver == NULL )
{
printf( "%s driver not availabel.\n", pszDriverName );
exit( 1 );
}
//创建数据源
GDALDataset *poDS;
//The ESRI Shapefile driver allows us to create a directory full of shapefiles, or a single shapefile as a datasource.
poDS = poDriver->Create( "point_out.shp", 0, 0, 0, GDT_Unknown, NULL );
if( poDS == NULL )
{
printf( "Creation of output file failed.\n" );
exit( 1 );
}
//创建输出图层
//In this case since the datasource is a single file, we can only have one layer.
OGRLayer *poLayer;
poLayer = poDS->CreateLayer( "point_out", NULL, wkbPoint, NULL ); //wkbPoint指定几何图形类型,也可设置参数指定坐标系等
if( poLayer == NULL )
{
printf( "Layer creation failed.\n" );
exit( 1 );
}
//创建属性字段
OGRFieldDefn oField( "Name", OFTString ); //Name字段
oField.SetWidth(32); //字段宽度
if( poLayer->CreateField( &oField ) != OGRERR_NONE )
{
printf( "Creating Name field failed.\n" );
exit( 1 );
}
double x, y;
char szName[33];
//In this case since the datasource is a single file, we can only have one layer.
while( ! feof(stdin) && fscanf( stdin, "%lf, %lf, %32s", &x, &y, szName ) == 3 )
{
//创建本地OGRFeature,设置属性
OGRFeature *poFeature;
poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() );
poFeature->SetField( "Name", szName );
//创建本地几何图形对象,将它的副本赋给feature
OGRPoint pt;
pt.setX( x );
pt.setY( y );
poFeature->SetGeometry( &pt );
//Now we create a feature in the file. The OGRLayer::CreateFeature() does not take ownership of our feature so we clean it up when done with it.
if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE )
{
printf( "Failed to create feature in shapfile.\n" );
exit( 1 );
}
OGRFeature::DestroyFeature( poFeature );
}
GDALClose( poDS );
}