[Gdal-dev] Error while writing to .shp file.
Mateusz Loskot
mateusz at loskot.net
Thu Jul 13 14:23:30 EDT 2006
Vidhiyadharan Nadarajah wrote:
> Hi,
>
> I want to add a feature to an existing polygon layer. Iam getting errors as
> follows.
>
> ERROR 3: Error in fseek() or fwrite() writing object to .shp file.
> ERROR 4: Failure writing .shp header.
Hi,
The problem is that you're opening datasource in read-only mode.
> Please find below the code Iam using and indicate me what is wrong.
>
> *********** start********
>
> #include "stdafx.h"
> #include "ogrsf_frmts.h"
>
>
> int main()
>
> {
>
> OGRRegisterAll();
> OGRDataSource *poDS;
> poDS =
> GRSFDriverRegistrar::Open( "C:\\Projects\\Test\\GDALTest\\shp\\india_ds.shp"
> , FALSE );
Note 1: There is no class called GRSFDriverRegistrar but
OGRSFDriverRegistrar.
Note 2: Change the second parameter from FALSE to TRUE.
> if( poDS == NULL )
> {
> printf( "Open failed.\n%s" );
> exit( 1 );
> }
>
> OGRLayer *poLayer;
> poLayer = poDS->GetLayerByName( "india_ds" );
>
> poLayer->ResetReading();
> if (NULL == poLayer)
> {
> printf("Layer not found\n");
> OGRDataSource::DestroyDataSource(poDS);
> return -1;
> }
>
>
> OGRFeature *poFeature = new OGRFeature( poLayer->GetLayerDefn() );
>
> // set the field
> poFeature->SetField( "State", "123" );
>
> OGRPoint *poPoint = new OGRPoint();
Remember to destroy the OGRPoint object pointed by poPoint
to avoid memory leak.
The member function
void OGRLineString::setPoint( int iPoint, OGRPoint * poPoint )
does not transfer ownership to point passed in.
Honestly, for better understanding this prototype should look as:
void OGRLineString::setPoint( int iPoint, const OGRPoint * poPoint )
because the poPoint is read-only inside the setPoint() function.
> OGRLinearRing *poLinearRing = new OGRLinearRing() ;
> poLinearRing->setNumPoints(4);
>
> poPoint->setX( 13 );
> poPoint->setY( 64 );
> poLinearRing->setPoint(0,poPoint);
>
> poPoint->setX( 13 );
> poPoint->setY( 66 );
> poLinearRing->setPoint(1,poPoint);
>
> poPoint->setX( 15 );
> poPoint->setY( 66 );
> poLinearRing->setPoint(2,poPoint);
>
> poPoint->setX( 15 );
> poPoint->setY( 64 );
> poLinearRing->setPoint(3,poPoint);
So, here is the deallocation:
delete poPoint;
> poLinearRing->closeRings();
>
>
> OGRPolygon *poOGRPolygon = new OGRPolygon();
> poOGRPolygon->addRingDirectly(poLinearRing);
>
>
> if(poFeature->SetGeometryDirectly( poOGRPolygon ) != OGRERR_NONE )
> {
> printf( "Failed to Set Geometry.\n" );
> exit( 1 );
>
> }
>
> if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE )
> {
> printf( "Failed to create feature in shapefile.\n" );
> exit( 1 );
> }
>
> delete poFeature;
>
> OGRDataSource::DestroyDataSource( poDS );
>
> return 0;
> }
Best regards
--
Mateusz Loskot
http://mateusz.loskot.net
More information about the Gdal-dev
mailing list