#include <ogrsf_frmts.h>
using namespace std;
int main()
{
GDALAllRegister();
GDALDriver * shpDriver;
const char *pszDriverName = "ESRI Shapefile";
shpDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName);
if (shpDriver == NULL)
{
printf("%s\n", "ESRI Shapefile驱动创建失败!");
return 0;
}
GDALDataset * ds = shpDriver->Create("./city/city.shp", 0, 0, 0, GDT_Unknown, NULL);
OGRSpatialReference oSR;
if (oSR.importFromEPSG(4326) != OGRERR_NONE)
{
printf("%s\n", "坐标系创建失败!");
return 0;
}
char **papszOptions = NULL;
papszOptions = CSLSetNameValue(papszOptions, "ENCODING", "UTF-8");
OGRLayer * oLay = ds->CreateLayer("city", &oSR, wkbPoint, papszOptions);
OGRFieldDefn oField("NAME", OFTString);
oField.SetWidth(10);
if (oLay->CreateField(&oField) != OGRERR_NONE)
{
printf("%s\n", "字段创建失败!");
return 0;
}
FILE * f = fopen("./city/city.csv", "r");
if (f == NULL)
{
printf("%s\n", "无法打开文件!");
return 0;
}
char name[100];
double x;
double y;
while (!feof(f))
{
CPLSetConfigOption("SHAPE_ENCODING", "");
fscanf(f, "%s%lf%lf\n", name, &x, &y);
OGRFeature *oFea;
oFea = OGRFeature::CreateFeature(oLay->GetLayerDefn());
OGRPoint oPoint;
oPoint.setX(x);
oPoint.setY(y);
oFea->SetGeometry(&oPoint);
oFea->SetField("NAME", name);
if (oLay->CreateFeature(oFea) != OGRERR_NONE)
{
printf("%s\n", "创建要素失败!");
return 0;
}
OGRFeature::DestroyFeature(oFea);
}
fclose(f);
system("pause");
return 0;
}
|