c++如何读取shp文件
时间: 2023-07-18 17:38:21 浏览: 131
在C++中,可以使用GDAL库来读取shp文件。下面是一个示例代码:
```cpp
#include <gdal/gdal_priv.h>
#include <gdal/ogrsf_frmts.h>
#include <iostream>
int main()
{
GDALAllRegister();
const char* filename = "path/to/shapefile.shp";
GDALDataset* dataset = (GDALDataset*)GDALOpenEx(filename, GDAL_OF_VECTOR, NULL, NULL, NULL);
if (dataset == NULL) {
std::cerr << "Failed to open shapefile " << filename << std::endl;
return 1;
}
OGRLayer* layer = dataset->GetLayer(0);
OGRFeature* feature;
layer->ResetReading();
while ((feature = layer->GetNextFeature()) != NULL) {
// do something with the feature
OGRFeature::DestroyFeature(feature);
}
GDALClose(dataset);
return 0;
}
```
其中,`path/to/shapefile.shp`需要替换为实际的shp文件路径。在代码中,首先调用`GDALAllRegister()`注册所有的GDAL驱动程序,然后通过`GDALOpenEx()`打开shapefile文件,获取`GDALDataset`对象。通过`GetLayer()`获取指定的图层,进而通过`GetNextFeature()`获取`OGRFeature`对象,遍历其中的feature即可。需要注意的是,在使用完feature后需要调用`OGRFeature::DestroyFeature()`销毁feature对象。
阅读全文