2016-01-22 80 views
0

我正在使用GDAL版本2.0.0。如何使用GDAL C++從shapefile中刪除特徵?

我有一個C++程序,我想從shapefile中刪除一個特徵。返回錯誤代碼表示成功刪除。但是,該功能保留在shapefile中。

是否有一些後續功能,我必須調用,以便刪除將持續?例如,當您對現有功能的字段進行更改時,必須再次調用OGRLayer::SetFeature(),否則該更改不會持續。

以下是我正在做的一個片段。 shapefile是通過對柵格文件進行多邊形化從頭開始創建的。然後我在關閉文件之前嘗試從該shape文件中刪除一個特徵。

#include <gdal_alg.h>  // GDALPolygonize() 
#include <gdal_priv.h> 

// 
// srcPath is the path of the soruce raster geospatial file. e.g., a GeoTIFF file. 
// tgtPath is the path of the target vector geospatial file. i.e., a shapefile. 
// 
void test(char const * srcPath, char const * tgtPath) 
{ 
    GDALAllRegister(); 

    // Open source file. 
    GDALDataset * pSrcDataset = static_cast<GDALDataset *>(GDALOpen(srcPath, GA_ReadOnly)); 

    GDALRasterBand * pSrcBand = pSrcDataset->GetRasterBand(1); 

    // Create and open target file. 
    GDALDriver * pDriver = GetGDALDriverManager()->GetDriverByName("ESRI Shapefile"); 
    GDALDataset * pTgtDataset = pDriver->Create(tgtPath, 0, 0, 0, GDT_Unknown, NULL); 

    // Create a layer. 
    OGRLayer * pTgtLayer = pTgtDataset->CreateLayer("layer", NULL, wkbPolygon, NULL); 

    // Create a field to contain value associated with each polygon feature. 
    OGRFieldDefn field("value", OFTInteger); 
    field.SetWidth(6); 
    pTgtLayer->CreateField(&field); 

    // Call GDALPolygonize to convert source raster to polygon features. 
    GDALRasterBand * pMaskBand = NULL; 
    int valueFieldIdx = 0; 
    char ** options = NULL; 
    GDALPolygonize(
    pSrcBand, 
    pMaskBand, 
    pTgtLayer, 
    valueFieldIdx, 
    options, 
    GDALTermProgress, NULL); 

    // Demonstrate that the target layer has the capability to delete a feature. 
    if (!pTgtLayer->TestCapability(OLCDeleteFeature)) 
    { 
    throw "Layer does not support delete feature capability"; 
    } 

    // Delete a feature that I know is there. 
    // The feature has a particular integer ID. 
    OGRErr err = pTgtLayer->DeleteFeature(12); 

    // Demonstrate that there is a zero error code, indicating successful deletion. 
    if (err != OGRERR_NONE) 
    { 
    throw "Failed to remove feature"; 
    } 

    // Close source and target files. 
    GDALClose(pSrcDataset); 
    GDALClose(pTgtDataset); 
} 
+0

什麼是pLayer?這是一個錯字嗎? –

+0

這確實是一個錯字。我修好了它。 –

回答

2

我從一位同事那裏瞭解到一些強制刪除特徵的文件中存在的東西。完成所有功能刪除後,在關閉shapefile之前,我執行以下操作。

// Delete features. 
    ... 

    // Flush pending changes. 
    pTgtLayer->SyncToDisk(); 

    // Execute a SQL command. 
    // It is essential, to force my changes to take effect. 
    // As a side effect, it renumbers the features to fill in 
    // the gaps left by deleted features. 
    stringstream sql; 
    sql << "REPACK " << pTgtLayer->GetName(); 
    pTgtDataset->ExecuteSQL(sql.str().c_str(), NULL, NULL); 

    // Close files. 
    ... 
+0

或者,它不是調用'OGRLayer :: SyncToDisk()',它也可以調用'GDALDataset :: FlushCache()',文檔說它會在所有圖層上調用'SyncToDisk()'。我測試了這個選擇,並且它也有效。 –

+0

如果你已經解決了問題,那麼爲什麼不接受你的答案呢? –