Exemple #1
0
    void parse(const std::string& path, Visitor& visitor) const
    {
        SHPHandle shpFile = SHPOpen(path.c_str(), "rb");
        if (shpFile == NULL)
            throw std::domain_error("Cannot open shp file.");

        int shapeType, entityCount;
        double adfMinBound[4], adfMaxBound[4];
        SHPGetInfo(shpFile, &entityCount, &shapeType, adfMinBound, adfMaxBound);

        DBFHandle dbfFile = DBFOpen(path.c_str(), "rb");
        if (dbfFile == NULL)
            throw std::domain_error("Cannot open dbf file.");

        if (DBFGetFieldCount(dbfFile) == 0)
            throw std::domain_error("There are no fields in dbf table.");

        if (entityCount != DBFGetRecordCount(dbfFile))
            throw std::domain_error("dbf file has different entity count.");

        for (int k = 0; k < entityCount; k++)
        {
            SHPObject* shape = SHPReadObject(shpFile, k);
            if (shape == NULL)
                throw std::domain_error("Unable to read shape:" + to_string(k));

            Tags tags = parseTags(dbfFile, k);
            visitShape(*shape, tags, visitor);

            SHPDestroyObject(shape);
        }

        DBFClose(dbfFile);
        SHPClose(shpFile);
    }
Exemple #2
0
// extract info from dbf
void
shapes_load_dbf(const char* filename, const char* column){

    DBFHandle hDBF;

    hDBF = DBFOpen( filename, "rb" );
    if( hDBF == NULL ) {
        fprintf(stderr, "DBFOpen(%s,\"r\") failed.\n", filename );
        return;
    }

    // INFO ABOUT DBF
    // int  *panWidth;
    // int  nWidth, nDecimals;
    // fprintf (stderr, "Info for %s\n", filename);
    // i = DBFGetFieldCount(hDBF);
    // fprintf (stderr, "%d Columns,  %d Records in file\n",i,DBFGetRecordCount(hDBF));
    // panWidth = (int *) malloc( DBFGetFieldCount( hDBF ) * sizeof(int) );
    // for( int i = 0; i < DBFGetFieldCount(hDBF); i++ ) {
    //     DBFFieldType    eType;
    //     char szTitle[256];
    //     eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
    //     fprintf(stderr, "%4d: %10s %c", i, szTitle, i%4 ? '|':'\n');
    // }
    // fprintf(stderr, "\n");

    // print names
    uint32_t fid = DBFGetFieldIndex(hDBF, column);
    for(uint32_t i = 0; i < DBFGetRecordCount(hDBF); i++ ) {
       char* name_long = (char *) DBFReadStringAttribute(hDBF, i, fid);
       fprintf(stderr, "%d: %s\n", i, name_long);
    }

    DBFClose( hDBF );
}
void
ShpLoaderDestroy(SHPLOADERSTATE *state)
{
	/* Destroy a state object created with ShpLoaderOpenShape */

	if (state != NULL)
	{
		if (state->hSHPHandle)
			SHPClose(state->hSHPHandle);
		if (state->hDBFHandle)
			DBFClose(state->hDBFHandle);
		if (state->field_names)
		{
			int i;
			for (i = 0; i < state->num_fields; i++)
				free(state->field_names[i]);

			free(state->field_names);
		}
		if (state->types)
			free(state->types);
		if (state->widths)
			free(state->widths);
		if (state->precisions)
			free(state->precisions);
		if (state->col_names)
			free(state->col_names);

		/* Free the state itself */
		free(state);
	}
}
Exemple #4
0
OGRShapeLayer::~OGRShapeLayer()

{
    if( m_nFeaturesRead > 0 && poFeatureDefn != NULL )
    {
        CPLDebug( "Shape", "%d features read on layer '%s'.",
                  (int) m_nFeaturesRead, 
                  poFeatureDefn->GetName() );
    }

    CPLFree( panMatchingFIDs );
    panMatchingFIDs = NULL;

    CPLFree( pszFullName );

    if( poFeatureDefn != NULL )
        poFeatureDefn->Release();

    if( poSRS != NULL )
        poSRS->Release();

    if( hDBF != NULL )
        DBFClose( hDBF );

    if( hSHP != NULL )
        SHPClose( hSHP );

    if( fpQIX != NULL )
        VSIFClose( fpQIX );
}
bool surfaceVectorField::CreateShape()
{
	char 	DataBaseID[64]="";

	hSHP=SHPCreate(ShapeFileName.c_str(), SHPT_POINT);
	if(hSHP==NULL)
		return false;
	SHPClose( hSHP );
	// Create the database.
	hDBF=DBFCreate(DataBaseName.c_str());
	if(hDBF==NULL)
		return false;

     //sprintf(DataBaseID, "%s", "Xcoord");
    	//DBFAddField(hDBF, DataBaseID, FTDouble, 16, 6);
     //sprintf(DataBaseID, "%s", "Ycoord");
    	//DBFAddField(hDBF, DataBaseID, FTDouble, 16, 6);
     sprintf(DataBaseID, "%s", "Windspd");
    	DBFAddField(hDBF, DataBaseID, FTDouble, 16, 6 );
     sprintf(DataBaseID, "%s", "Winddir");
    	DBFAddField(hDBF, DataBaseID, FTInteger, 8, 0);
     sprintf(DataBaseID, "%s", "AV_dir");
    	DBFAddField(hDBF, DataBaseID, FTInteger, 8, 0 );
     sprintf(DataBaseID, "%s", "AM_dir");
    	DBFAddField(hDBF, DataBaseID, FTInteger, 8, 0 );
	DBFClose(hDBF);

     return true;
}
Exemple #6
0
DBFHandle DBFCloneEmpty(DBFHandle psDBF, const char * pszFilename ) 
{
    DBFHandle	newDBF;

   newDBF = DBFCreate ( pszFilename );
   if ( newDBF == NULL ) return ( NULL ); 
   
   newDBF->pszHeader = (char *) malloc ( 32 * psDBF->nFields );
   memcpy ( newDBF->pszHeader, psDBF->pszHeader, 32 * psDBF->nFields );
   
   newDBF->nFields = psDBF->nFields;
   newDBF->nRecordLength = psDBF->nRecordLength;
   newDBF->nHeaderLength = psDBF->nHeaderLength;
    
   newDBF->panFieldOffset = (int *) malloc ( sizeof(int) * psDBF->nFields ); 
   memcpy ( newDBF->panFieldOffset, psDBF->panFieldOffset, sizeof(int) * psDBF->nFields );
   newDBF->panFieldSize = (int *) malloc ( sizeof(int) * psDBF->nFields );
   memcpy ( newDBF->panFieldSize, psDBF->panFieldSize, sizeof(int) * psDBF->nFields );
   newDBF->panFieldDecimals = (int *) malloc ( sizeof(int) * psDBF->nFields );
   memcpy ( newDBF->panFieldDecimals, psDBF->panFieldDecimals, sizeof(int) * psDBF->nFields );
   newDBF->pachFieldType = (char *) malloc ( sizeof(int) * psDBF->nFields );
   memcpy ( newDBF->pachFieldType, psDBF->pachFieldType, sizeof(int) * psDBF->nFields );

   newDBF->bNoHeader = TRUE;
   newDBF->bUpdated = TRUE;
   
   DBFWriteHeader ( newDBF );
   DBFClose ( newDBF );
   
   newDBF = DBFOpen ( pszFilename, "rb+" );

   return ( newDBF );
}
Exemple #7
0
int CDbfFile::DBFAddRecord(CStringArray* psDBFFieldValList)
{
    DBFHandle	hDBF;
	int			i;
	int			iRecord;
	int			iNumField;

	if (psDBFFieldValList == NULL)
		iNumField = 0;
	else
		iNumField = psDBFFieldValList->GetSize();

    // Open/Create the database.						
	hDBF = DBFOpen("r+b" );
	if( hDBF == NULL )
	{
		printf("DBFOpen failed: %s", _szDBFName);
		return 1;
	}
    
	// Do we have the correct number of arguments?			
	if( DBFGetFieldCount( hDBF ) != iNumField )
	{
		CString sMsg;
		sMsg.Format("Received %d field(s), but require %d field(s).",iNumField,DBFGetFieldCount(hDBF));
		printf("%s\n",sMsg);

		int		i, iWidth, iDecimals;
		char	psName[257];

		for (i=0; i<DBFGetFieldCount(hDBF); i++)
		{
			DBFGetFieldInfo(hDBF,i,psName,&iWidth,&iDecimals);
			sMsg.Format("%d of %d) FieldName: %s    Width: %d    Decimals: %d",i+1,DBFGetFieldCount(hDBF),psName,iWidth,iDecimals);
			printf("%s\n",sMsg);
		}
		return 1;
	}

	iRecord = DBFGetRecordCount( hDBF );

/* -------------------------------------------------------------------- */
/*	Loop assigning the new field values.				*/
/* -------------------------------------------------------------------- */
	for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
	{
		if( DBFGetFieldInfo( hDBF, i, NULL, NULL, NULL ) == FTString )
			DBFWriteStringAttribute(hDBF, iRecord, i, psDBFFieldValList->GetAt(i) );
		else
			DBFWriteDoubleAttribute(hDBF, iRecord, i, atof(psDBFFieldValList->GetAt(i)) );
	}

/* -------------------------------------------------------------------- */
/*      Close and cleanup.                                              */
/* -------------------------------------------------------------------- */
	DBFClose( hDBF );

	return 0;
}
Exemple #8
0
/**

 * \brief Checks DBF file existance and validity
 *
 * \param dbf_file path and file name of DBF file
 *
 * \return Returns true if existing and valid
 * */
bool dbf_file_exists(const char* dbf_file) {
    DBFHandle handle = DBFOpen(dbf_file, "rb");
    if (handle == NULL) {
        return false;
    }
    DBFClose(handle);
    return true;
}
Exemple #9
0
int main( int argc, char ** argv )

{
    DBFHandle	hDBF;
    int		i, iRecord;

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( argc < 3 )
    {
	printf( "dbfadd xbase_file field_values\n" );

	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*	Create the database.						*/
/* -------------------------------------------------------------------- */
    hDBF = DBFOpen( argv[1], "r+b" );
    if( hDBF == NULL )
    {
	printf( "DBFOpen(%s,\"rb+\") failed.\n", argv[1] );
	exit( 2 );
    }
    
/* -------------------------------------------------------------------- */
/*	Do we have the correct number of arguments?			*/
/* -------------------------------------------------------------------- */
    if( DBFGetFieldCount( hDBF ) != argc - 2 )
    {
	printf( "Got %d fields, but require %d\n",
	        argc - 2, DBFGetFieldCount( hDBF ) );
	exit( 3 );
    }

    iRecord = DBFGetRecordCount( hDBF );

/* -------------------------------------------------------------------- */
/*	Loop assigning the new field values.				*/
/* -------------------------------------------------------------------- */
    for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
    {
        if( strcmp( argv[i+2], "" ) == 0 )
            DBFWriteNULLAttribute(hDBF, iRecord, i );
	else if( DBFGetFieldInfo( hDBF, i, NULL, NULL, NULL ) == FTString )
	    DBFWriteStringAttribute(hDBF, iRecord, i, argv[i+2] );
	else
	    DBFWriteDoubleAttribute(hDBF, iRecord, i, atof(argv[i+2]) );
    }

/* -------------------------------------------------------------------- */
/*      Close and cleanup.                                              */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );

    return( 0 );
}
void rspfShapeDatabase::close()
{
    if(isOpen())
    {
        DBFClose(theHandle);
        theHandle = NULL;
        theRecordNumber = -1;
    }
}
void close_baseline_shape(DBFHandle dbase, SHPHandle shape)
{
    // Close database
    DBFClose(dbase);
    dbase = NULL;

    // Close shapefile
    SHPClose(shape);
    shape = NULL;
}
Exemple #12
0
 void close() {
     if (m_dbf_handle) {
         DBFClose(m_dbf_handle);
         m_dbf_handle = 0;
     }
     if (m_shp_handle) {
         SHPClose(m_shp_handle);
         m_shp_handle = 0;
     }
 }
Exemple #13
0
int CDbfFile::AddDBF4(char* psDBFAttList,CString sDelimiter, int nSize)
//used when strings separated by '\0'
{
	DBFHandle	hDBF;

	int			kk;
	CFileFind	ShapeFile;
	CString		sTmp;
	CStringArray	*psDBFAtt;
	psDBFAtt = new CStringArray();

	if (_bInit)
	{
		_bInit = false;
		ValidateDBF();
		DBFSetColumn(&_psDBFAttList);
	}
    // Open/Create the database.						
	hDBF = DBFOpen("r+b" );
	if( hDBF == NULL )
	{
		printf("DBFOpen failed: %s\n", _szDBFName);
		return 1;
	}
	
	int nStrStart = 0;
	for (kk = 0; kk < nSize; kk++)
	{
		psDBFAtt->RemoveAll();
		sTmp = "";
		while(psDBFAttList[nStrStart]!='\0')
		{
			sTmp = sTmp + psDBFAttList[nStrStart++];
		}
		nStrStart++;
		while (sTmp.Find(sDelimiter) != -1)
		{
			psDBFAtt->Add(sTmp.Left(sTmp.Find(sDelimiter)));
			sTmp.Delete(0, (sTmp.Find(sDelimiter) + 1));
		}
		if (!sTmp.IsEmpty())
			psDBFAtt->Add(sTmp);
		DBFAddRecord(hDBF, psDBFAtt);

	}

	psDBFAtt->RemoveAll();

/* -------------------------------------------------------------------- */
/*      Close and cleanup.                                              */
/* -------------------------------------------------------------------- */
	DBFClose( hDBF );
	delete(psDBFAtt);
	return 0;
}
jboolean Java_org_maptools_shapelib_android_util_TestUtils_updateShapefile(JNIEnv * env, jclass clazz,
                                                                jstring file, jobject listObject) {
    // open an existing shapefile and dbf (e.g. /sdcard/foo/bar)
    const char *fileStr = (*env)->GetStringUTFChars(env, file, 0);
    SHPHandle hSHP = SHPOpen(fileStr, "rb+");
    DBFHandle hDBF = DBFOpen(fileStr, "rb+");
    (*env)->ReleaseStringUTFChars(env, file, fileStr);

    process(env, hSHP, hDBF, file, listObject);

    SHPClose(hSHP);
    DBFClose(hDBF);
}
Exemple #15
0
int CDbfFile::AddDBF(CStringArray* psDBFAttList,CString sDelimiter)
{
	DBFHandle	hDBF;

	int			kk;
	CFileFind	ShapeFile;
	CString		sTmp;
	CStringArray	*psDBFAtt;
	psDBFAtt = new CStringArray();

	if (_bInit)
	{
		_bInit = false;
		ValidateDBF();
		DBFSetColumn(&_psDBFAttList);
	}
    // Open/Create the database.						
	hDBF = DBFOpen("r+b" );
	if( hDBF == NULL )
	{
		printf("DBFOpen failed: %s\n", _szDBFName);
		return 1;
	}

	for (kk = 0; kk < psDBFAttList->GetSize(); kk++)
	{
		psDBFAtt->RemoveAll();
		sTmp = psDBFAttList->GetAt(kk);
		while (sTmp.Find(sDelimiter) != -1)
		{
			psDBFAtt->Add(sTmp.Left(sTmp.Find(sDelimiter)));
			sTmp.Delete(0, (sTmp.Find(sDelimiter) + 1));
		}
		if (!sTmp.IsEmpty())
			psDBFAtt->Add(sTmp);
		DBFAddRecord(hDBF, psDBFAtt);
	}

	psDBFAtt->RemoveAll();

/* -------------------------------------------------------------------- */
/*      Close and cleanup.                                              */
/* -------------------------------------------------------------------- */
	DBFClose( hDBF );
	delete(psDBFAtt);
	return 0;
}
jboolean Java_org_maptools_shapelib_android_util_TestUtils_createShapefile(JNIEnv * env, jclass clazz,
                                                                jstring file, jobject listObject) {
    // create a shapefile and dbf (e.g. /sdcard/foo/bar)
    const char *fileStr = (*env)->GetStringUTFChars(env, file, 0);
    SHPHandle hSHP = SHPCreate(fileStr, SHPT_POINT);
    DBFHandle hDBF = DBFCreate(fileStr);

    // define the shapefile attributes
    DBFAddField(hDBF, "name", FTString, 25, 0);
    DBFAddField(hDBF, "height", FTDouble, 8, 8);
    DBFAddField(hDBF, "apples", FTInteger, 1, 0);

    process(env, hSHP, hDBF, file, listObject);

    SHPClose(hSHP);
    DBFClose(hDBF);
}
static int display_info(const char * fpath, const struct stat * sb, int tflag, struct FTW * ftwbuf)
{
  if (fpath[ftwbuf->base] == '.') return 0;
  if (strcmp(fpath + strlen(fpath) - 4, ".dbf") != 0) return 0;
  
  char file[400];
  strncpy(file, fpath + strlen(data_path), 400);
  file[strlen(file)-4] = 0;
  
  DBFHandle dbf = DBFOpen(fpath, "rb");
  SHPHandle shp = SHPOpen(fpath, "rb");
  
  general_count++;
  
  char * formatc = mg_get_var(dconn, "format");
  int json = 0;
  if (formatc != NULL && strcmp(formatc, "json") == 0)
    json = 1;
  free(formatc);
  
  if (json)
  {
    mg_printf(dconn, "%s\n  {", ((general_count==1) ? "" : ","));
    mg_printf(dconn, "\"file\":\"%s\"", file);
    
    if (dbf) mg_printf(dconn, ", \"dbfRecords\":%d", dbf->nRecords);
    if (dbf) mg_printf(dconn, ", \"dbfFields\":%d", dbf->nFields);
    
    mg_printf(dconn, ", \"image 0\": \"/image?file=%s&id=0\"", file);
    mg_printf(dconn, ", \"full image\": \"/image?file=%s\"", file);
    mg_printf(dconn, "}");
  }
  else
  {
    mg_printf(dconn, "<tr>");
    mg_printf(dconn, "<td>%s</td>", file);
    if (dbf) mg_printf(dconn, "<td><a href='/shapefiles/fields?file=%s'>fields</a></td>", file);
    if (shp) mg_printf(dconn, "<td><a href='/shapefiles/png?file=%s'>image</a></td>\n", file);
    mg_printf(dconn, "</tr>");
  }
  
  if (shp) SHPClose(shp);
  if (dbf) DBFClose(dbf);
  
  return 0; // To tell nftw() to continue
}
void
ShpLoaderDestroy(SHPLOADERSTATE *state)
{
	/* Destroy a state object created with ShpLoaderOpenShape */
	int i;
	if (state != NULL)
	{
		if (state->hSHPHandle)
			SHPClose(state->hSHPHandle);
		if (state->hDBFHandle)
			DBFClose(state->hDBFHandle);
		if (state->field_names)
		{
			for (i = 0; i < state->num_fields; i++)
				free(state->field_names[i]);

			free(state->field_names);
		}
		if (state->pgfieldtypes)
		{
			for (i = 0; i < state->num_fields; i++)
				free(state->pgfieldtypes[i]);

			free(state->pgfieldtypes);
		}
		if (state->types)
			free(state->types);
		if (state->widths)
			free(state->widths);
		if (state->precisions)
			free(state->precisions);
		if (state->col_names)
			free(state->col_names);

		/* Free any column map fieldnames if specified */
		colmap_clean(&state->column_map);

		/* Free the state itself */
		free(state);
	}
}
void shapefiles_fields(struct mg_connection *conn, const struct mg_request_info *ri, void *data)
{
  char * file = mg_get_var(conn, "file");
  if (file == NULL) { mg_printf(conn, "You need to specify a file."); return; }
  
  char filename[100];
  sprintf(filename, "/work/data/%s", file);
  
  DBFHandle dbf = DBFOpen(filename, "rb");
  if (dbf == NULL) { mg_printf(conn, "DBFOpen error (%s)\n", filename); return; }
  
  int nRecordCount = DBFGetRecordCount(dbf);
  int nFieldCount = DBFGetFieldCount(dbf);
  
  mg_printf(conn, "{\n");
  mg_printf(conn, "  \"file\": \"%s\",\n", file);
  mg_printf(conn, "  \"num_records\": \"%d\",\n", nRecordCount);
  mg_printf(conn, "  \"fields\": {\n");
  for (int i = 0 ; i < nFieldCount ; i++)
  {
    char pszFieldName[12];
    int pnWidth; int pnDecimals;
    char type_names[5][20] = {"string", "integer", "double", "logical", "invalid"};
    
    DBFFieldType ft = DBFGetFieldInfo(dbf, i, pszFieldName, &pnWidth, &pnDecimals);
    mg_printf(conn, "    \"%d\": {\n", i);
    mg_printf(conn, "      \"name\":\"%s\",\n", pszFieldName);
    if (pnWidth != 0) mg_printf(conn, "      \"width\":\"%d\",\n", pnWidth);
    if (pnDecimals != 0) mg_printf(conn, "      \"decimals\":\"%d\",\n", pnDecimals);
    mg_printf(conn, "      \"type\":\"%s\"\n", type_names[ft]);
    mg_printf(conn, "    }%s\n", (i==nFieldCount-1)?"":",");
  }
  mg_printf(conn, "  }\n");
  mg_printf(conn, "}\n");
  
  if (dbf != NULL) DBFClose(dbf);
  free(file);
}
Exemple #20
0
int isshape(char *inFile)
{
    char *ext = findExt(inFile);
    if (ext && strcmp_case(ext,".shp")!=0) {
        return FALSE;
    }

    char *dbaseFile, *basename;
    int isShape = 0;
    int nEntities, pointType;
    DBFHandle dbase;
    SHPHandle shape;

    dbaseFile = (char *)MALLOC(sizeof(char)*(strlen(inFile)+5));
    basename = get_basename(inFile);
    sprintf(dbaseFile, "%s.dbf", basename);
    dbase = DBFOpen(dbaseFile, "r+b");
    shape = SHPOpen(inFile, "r+b");
    if (dbase != NULL && shape != NULL) {
        SHPGetInfo(shape, &nEntities, &pointType, NULL, NULL);
        if (nEntities >= 1 &&
            (pointType == SHPT_POLYGON   ||
             pointType == SHPT_POINT     ||
             pointType == SHPT_ARC       ||
             pointType == SHPT_MULTIPOINT )
        )
        {
            isShape = 1;
        }
    }
    if (shape) SHPClose(shape);
    if (dbase) DBFClose(dbase);
    FREE(basename);
    FREE(dbaseFile);

    return isShape;
}
Exemple #21
0
strings_v
shape_load_names(const char* filename, const char* colname) {

    DBFHandle hDBF;
    strings_v col;
    kv_init(col);

    hDBF = DBFOpen( filename, "rb" );
    if( hDBF == NULL ) {
        fprintf(stderr, "DBFOpen(%s,\"r\") failed.\n", filename );
        return col;
    }
    uint32_t fid = DBFGetFieldIndex(hDBF, colname);
    for(uint32_t i = 0; i < DBFGetRecordCount(hDBF); i++ ) {
        char* str = (char *) DBFReadStringAttribute(hDBF, i, fid);
        if(str != NULL)
            kv_push(char*, col, strdup(str));
        else            
            kv_push(char*, col, NULL);
    }

    DBFClose( hDBF );
    return col;
}
Exemple #22
0
int main( int argc, char ** argv )

{
    SHPHandle	old_SHP, new_SHP;
    DBFHandle   old_DBF, new_DBF;
    int		nShapeType, nEntities, nVertices, nParts, *panParts, i, iPart;
    double	*padVertices, adBounds[4];
    const char 	*pszPlus;
    DBFFieldType  idfld_type;
    int		idfld, nflds;
    char	kv[257] = "";
    char	idfldName[120] = "";
    char	fldName[120] = "";
    char	shpFileName[120] = "";
    char	dbfFileName[120] = "";
    char	*DBFRow = NULL;
    int		Cpan[2] = { 0,0 };
    int		byRing = 1;
    PT		oCentrd, ringCentrd;
    SHPObject	*psCShape, *cent_pt;
    double	oArea = 0.0, oLen = 0.0;

    if( argc < 2 )
    {
	printf( "shpdata shp_file \n" );
	exit( 1 );
    }
    
    old_SHP = SHPOpen (argv[1], "rb" );
    old_DBF = DBFOpen (argv[1], "rb");
    if( old_SHP == NULL || old_DBF == NULL )
    {
	printf( "Unable to open old files:%s\n", argv[1] );
	exit( 1 );
    }

    SHPGetInfo( old_SHP, &nEntities, &nShapeType, NULL, NULL );
    for( i = 0; i < nEntities; i++ )
    {
	int		res ;

	psCShape = SHPReadObject( old_SHP, i );

        if ( byRing == 1 ) {
          int 	   ring, prevStart, ringDir;
	  double   ringArea;

          prevStart = psCShape->nVertices;
          for ( ring = (psCShape->nParts - 1); ring >= 0; ring-- ) {
	    SHPObject 	*psO;
	    int		j, numVtx, rStart;
            
            rStart = psCShape->panPartStart[ring];
            if ( ring == (psCShape->nParts -1) )
              { numVtx = psCShape->nVertices - rStart; }
             else
              { numVtx = psCShape->panPartStart[ring+1] - rStart; }
              
            printf ("(shpdata) Ring(%d) (%d for %d) \n", ring, rStart, numVtx);              
	    psO = SHPClone ( psCShape, ring,  ring + 1 );

            ringDir = SHPRingDir_2d ( psO, 0 );
            ringArea = RingArea_2d (psO->nVertices,(double*) psO->padfX,
            	 (double*) psO->padfY);
            RingCentroid_2d ( psO->nVertices, (double*) psO->padfX, 
     		(double*) psO->padfY, &ringCentrd, &ringArea);  

            	 
            printf ("(shpdata)  Ring %d, %f Area %d dir \n", 
           	ring, ringArea, ringDir );

	    SHPDestroyObject ( psO );
            printf ("(shpdata) End Ring \n");
           }  /* (ring) [0,nParts  */

          }  /* by ring   */

	   oArea = SHPArea_2d ( psCShape );
	   oLen = SHPLength_2d ( psCShape ); 
	   oCentrd = SHPCentrd_2d ( psCShape );
           printf ("(shpdata) Part (%d) %f Area  %f length, C (%f,%f)\n",
           	 i, oArea, oLen, oCentrd.x, oCentrd.y );
    }

    SHPClose( old_SHP );

    DBFClose( old_DBF );

    printf ("\n");
}
Exemple #23
0
int main( int argc, char ** argv )

{
    DBFHandle	hDBF;
    int		*panWidth, i, iRecord;
    char	szFormat[32], *pszFilename = NULL;
    int		nWidth, nDecimals;
    int		bHeader = 0;
    int		bRaw = 0;
    int		bMultiLine = 0;
    char	szTitle[12];

/* -------------------------------------------------------------------- */
/*      Handle arguments.                                               */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( strcmp(argv[i],"-h") == 0 )
            bHeader = 1;
        else if( strcmp(argv[i],"-r") == 0 )
            bRaw = 1;
        else if( strcmp(argv[i],"-m") == 0 )
            bMultiLine = 1;
        else
            pszFilename = argv[i];
    }

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( pszFilename == NULL )
    {
	printf( "dbfdump [-h] [-r] [-m] xbase_file\n" );
        printf( "        -h: Write header info (field descriptions)\n" );
        printf( "        -r: Write raw field info, numeric values not reformatted\n" );
        printf( "        -m: Multiline, one line per field.\n" );
	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Open the file.                                                  */
/* -------------------------------------------------------------------- */
    hDBF = DBFOpen( pszFilename, "rb" );
    if( hDBF == NULL )
    {
	printf( "DBFOpen(%s,\"r\") failed.\n", argv[1] );
	exit( 2 );
    }
    
/* -------------------------------------------------------------------- */
/*	If there is no data in this file let the user know.		*/
/* -------------------------------------------------------------------- */
    if( DBFGetFieldCount(hDBF) == 0 )
    {
	printf( "There are no fields in this table!\n" );
	exit( 3 );
    }

/* -------------------------------------------------------------------- */
/*	Dump header definitions.					*/
/* -------------------------------------------------------------------- */
    if( bHeader )
    {
        for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
        {
            DBFFieldType	eType;
            const char	 	*pszTypeName;

            eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
            if( eType == FTString )
                pszTypeName = "String";
            else if( eType == FTInteger )
                pszTypeName = "Integer";
            else if( eType == FTDouble )
                pszTypeName = "Double";
            else if( eType == FTInvalid )
                pszTypeName = "Invalid";

            printf( "Field %d: Type=%s, Title=`%s', Width=%d, Decimals=%d\n",
                    i, pszTypeName, szTitle, nWidth, nDecimals );
        }
    }

/* -------------------------------------------------------------------- */
/*	Compute offsets to use when printing each of the field 		*/
/*	values. We make each field as wide as the field title+1, or 	*/
/*	the field value + 1. 						*/
/* -------------------------------------------------------------------- */
    panWidth = (int *) malloc( DBFGetFieldCount( hDBF ) * sizeof(int) );

    for( i = 0; i < DBFGetFieldCount(hDBF) && !bMultiLine; i++ )
    {
	DBFFieldType	eType;

	eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );
	if( strlen(szTitle) > nWidth )
	    panWidth[i] = strlen(szTitle);
	else
	    panWidth[i] = nWidth;

	if( eType == FTString )
	    sprintf( szFormat, "%%-%ds ", panWidth[i] );
	else
	    sprintf( szFormat, "%%%ds ", panWidth[i] );
	printf( szFormat, szTitle );
    }
    printf( "\n" );

/* -------------------------------------------------------------------- */
/*	Read all the records 						*/
/* -------------------------------------------------------------------- */
    for( iRecord = 0; iRecord < DBFGetRecordCount(hDBF); iRecord++ )
    {
        if( bMultiLine )
            printf( "Record: %d\n", iRecord );
        
	for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
	{
            DBFFieldType	eType;
            
            eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals );

            if( bMultiLine )
            {
                printf( "%s: ", szTitle );
            }
            
/* -------------------------------------------------------------------- */
/*      Print the record according to the type and formatting           */
/*      information implicit in the DBF field description.              */
/* -------------------------------------------------------------------- */
            if( !bRaw )
            {
                if( DBFIsAttributeNULL( hDBF, iRecord, i ) )
                {
                    if( eType == FTString )
                        sprintf( szFormat, "%%-%ds", nWidth );
                    else
                        sprintf( szFormat, "%%%ds", nWidth );

                    printf( szFormat, "(NULL)" );
                }
                else
                {
                    switch( eType )
                    {
                      case FTString:
                        sprintf( szFormat, "%%-%ds", nWidth );
                        printf( szFormat, 
                                DBFReadStringAttribute( hDBF, iRecord, i ) );
                        break;
                        
                      case FTInteger:
                        sprintf( szFormat, "%%%dd", nWidth );
                        printf( szFormat, 
                                DBFReadIntegerAttribute( hDBF, iRecord, i ) );
                        break;
                        
                      case FTDouble:
                        sprintf( szFormat, "%%%d.%dlf", nWidth, nDecimals );
                        printf( szFormat, 
                                DBFReadDoubleAttribute( hDBF, iRecord, i ) );
                        break;
                        
                      default:
                        break;
                    }
                }
            }

/* -------------------------------------------------------------------- */
/*      Just dump in raw form (as formatted in the file).               */
/* -------------------------------------------------------------------- */
            else
            {
                sprintf( szFormat, "%%-%ds", nWidth );
                printf( szFormat, 
                        DBFReadStringAttribute( hDBF, iRecord, i ) );
            }

/* -------------------------------------------------------------------- */
/*      Write out any extra spaces required to pad out the field        */
/*      width.                                                          */
/* -------------------------------------------------------------------- */
	    if( !bMultiLine )
	    {
		sprintf( szFormat, "%%%ds", panWidth[i] - nWidth + 1 );
		printf( szFormat, "" );
	    }

            if( bMultiLine )
                printf( "\n" );

	    fflush( stdout );
	}
	printf( "\n" );
    }

    DBFClose( hDBF );

    return( 0 );
}
Exemple #24
0
OGRErr OGRShapeLayer::Repack()

{
    if( !bUpdateAccess )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
            "The REPACK operation is not permitted on a read-only shapefile." );
        return OGRERR_FAILURE;
    }
    
    if( hDBF == NULL )
    {
        CPLError( CE_Failure, CPLE_NotSupported, 
                  "Attempt to repack a shapefile with no .dbf file not supported.");
        return OGRERR_FAILURE;
    }
    
/* -------------------------------------------------------------------- */
/*      Build a list of records to be dropped.                          */
/* -------------------------------------------------------------------- */
    int *panRecordsToDelete = (int *) 
        CPLMalloc(sizeof(int)*(nTotalShapeCount+1));
    int nDeleteCount = 0;
    int iShape = 0;
    OGRErr eErr = OGRERR_NONE;

    for( iShape = 0; iShape < nTotalShapeCount; iShape++ )
    {
        if( DBFIsRecordDeleted( hDBF, iShape ) )
            panRecordsToDelete[nDeleteCount++] = iShape;
    }
    panRecordsToDelete[nDeleteCount] = -1;

/* -------------------------------------------------------------------- */
/*      If there are no records marked for deletion, we take no         */
/*      action.                                                         */
/* -------------------------------------------------------------------- */
    if( nDeleteCount == 0 )
    {
        CPLFree( panRecordsToDelete );
        return OGRERR_NONE;
    }

/* -------------------------------------------------------------------- */
/*      Find existing filenames with exact case (see #3293).            */
/* -------------------------------------------------------------------- */
    CPLString osDirname(CPLGetPath(pszFullName));
    CPLString osBasename(CPLGetBasename(pszFullName));
    
    CPLString osDBFName, osSHPName, osSHXName;
    char **papszCandidates = CPLReadDir( osDirname );
    int i = 0;
    while(papszCandidates != NULL && papszCandidates[i] != NULL)
    {
        CPLString osCandidateBasename = CPLGetBasename(papszCandidates[i]);
        CPLString osCandidateExtension = CPLGetExtension(papszCandidates[i]);
        if (osCandidateBasename.compare(osBasename) == 0)
        {
            if (EQUAL(osCandidateExtension, "dbf"))
                osDBFName = CPLFormFilename(osDirname, papszCandidates[i], NULL);
            else if (EQUAL(osCandidateExtension, "shp"))
                osSHPName = CPLFormFilename(osDirname, papszCandidates[i], NULL);
            else if (EQUAL(osCandidateExtension, "shx"))
                osSHXName = CPLFormFilename(osDirname, papszCandidates[i], NULL);
        }
        
        i++;
    }
    CSLDestroy(papszCandidates);
    papszCandidates = NULL;
    
    if (osDBFName.size() == 0)
    {
        /* Should not happen, really */
        CPLFree( panRecordsToDelete );
        return OGRERR_FAILURE;
    }
    
/* -------------------------------------------------------------------- */
/*      Cleanup any existing spatial index.  It will become             */
/*      meaningless when the fids change.                               */
/* -------------------------------------------------------------------- */
    if( CheckForQIX() )
        DropSpatialIndex();

/* -------------------------------------------------------------------- */
/*      Create a new dbf file, matching the old.                        */
/* -------------------------------------------------------------------- */
    DBFHandle hNewDBF = NULL;
    
    CPLString oTempFile(CPLFormFilename(osDirname, osBasename, NULL));
    oTempFile += "_packed.dbf";

    hNewDBF = DBFCloneEmpty( hDBF, oTempFile );
    if( hNewDBF == NULL )
    {
        CPLFree( panRecordsToDelete );

        CPLError( CE_Failure, CPLE_OpenFailed, 
                  "Failed to create temp file %s.", 
                  oTempFile.c_str() );
        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Copy over all records that are not deleted.                     */
/* -------------------------------------------------------------------- */
    int iDestShape = 0;
    int iNextDeletedShape = 0;

    for( iShape = 0; 
         iShape < nTotalShapeCount && eErr == OGRERR_NONE; 
         iShape++ )
    {
        if( panRecordsToDelete[iNextDeletedShape] == iShape )
            iNextDeletedShape++;
        else
        {
            void *pTuple = (void *) DBFReadTuple( hDBF, iShape );
            if( pTuple == NULL )
                eErr = OGRERR_FAILURE;
            else if( !DBFWriteTuple( hNewDBF, iDestShape++, pTuple ) )
                eErr = OGRERR_FAILURE;
        }                           
    }

    if( eErr != OGRERR_NONE )
    {
        CPLFree( panRecordsToDelete );
        VSIUnlink( oTempFile );
        return eErr;
    }

/* -------------------------------------------------------------------- */
/*      Cleanup the old .dbf and rename the new one.                    */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    DBFClose( hNewDBF );
    hDBF = hNewDBF = NULL;
    
    VSIUnlink( osDBFName );
        
    if( VSIRename( oTempFile, osDBFName ) != 0 )
    {
        CPLDebug( "Shape", "Can not rename DBF file: %s", VSIStrerror( errno ) );
        CPLFree( panRecordsToDelete );
        return OGRERR_FAILURE;
    }
    
/* -------------------------------------------------------------------- */
/*      Now create a shapefile matching the old one.                    */
/* -------------------------------------------------------------------- */
    if( hSHP != NULL )
    {
        SHPHandle hNewSHP = NULL;
        
        if (osSHPName.size() == 0 || osSHXName.size() == 0)
        {
            /* Should not happen, really */
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }

        oTempFile = CPLFormFilename(osDirname, osBasename, NULL);
        oTempFile += "_packed.shp";

        hNewSHP = SHPCreate( oTempFile, hSHP->nShapeType );
        if( hNewSHP == NULL )
        {
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }

/* -------------------------------------------------------------------- */
/*      Copy over all records that are not deleted.                     */
/* -------------------------------------------------------------------- */
        iNextDeletedShape = 0;

        for( iShape = 0; 
             iShape < nTotalShapeCount && eErr == OGRERR_NONE; 
             iShape++ )
        {
            if( panRecordsToDelete[iNextDeletedShape] == iShape )
                iNextDeletedShape++;
            else
            {
                SHPObject *hObject;

                hObject = SHPReadObject( hSHP, iShape );
                if( hObject == NULL )
                    eErr = OGRERR_FAILURE;
                else if( SHPWriteObject( hNewSHP, -1, hObject ) == -1 )
                    eErr = OGRERR_FAILURE;

                if( hObject )
                    SHPDestroyObject( hObject );
            }
        }

        if( eErr != OGRERR_NONE )
        {
            CPLFree( panRecordsToDelete );
            VSIUnlink( CPLResetExtension( oTempFile, "shp" ) );
            VSIUnlink( CPLResetExtension( oTempFile, "shx" ) );
            return eErr;
        }

/* -------------------------------------------------------------------- */
/*      Cleanup the old .shp/.shx and rename the new one.               */
/* -------------------------------------------------------------------- */
        SHPClose( hSHP );
        SHPClose( hNewSHP );
        hSHP = hNewSHP = NULL;

        VSIUnlink( osSHPName );
        VSIUnlink( osSHXName );

        oTempFile = CPLResetExtension( oTempFile, "shp" );
        if( VSIRename( oTempFile, osSHPName ) != 0 )
        {
            CPLDebug( "Shape", "Can not rename SHP file: %s", VSIStrerror( errno ) );
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }
    
        oTempFile = CPLResetExtension( oTempFile, "shx" );
        if( VSIRename( oTempFile, osSHXName ) != 0 )
        {
            CPLDebug( "Shape", "Can not rename SHX file: %s", VSIStrerror( errno ) );
            CPLFree( panRecordsToDelete );
            return OGRERR_FAILURE;
        }
    }
    
    CPLFree( panRecordsToDelete );
    panRecordsToDelete = NULL;

/* -------------------------------------------------------------------- */
/*      Reopen the shapefile                                            */
/*                                                                      */
/* We do not need to reimplement OGRShapeDataSource::OpenFile() here    */  
/* with the fully featured error checking.                              */
/* If all operations above succeeded, then all necessery files are      */
/* in the right place and accessible.                                   */
/* -------------------------------------------------------------------- */
    CPLAssert( NULL == hSHP );
    CPLAssert( NULL == hDBF && NULL == hNewDBF );
    
    CPLPushErrorHandler( CPLQuietErrorHandler );
    
    const char* pszAccess = NULL;
    if( bUpdateAccess )
        pszAccess = "r+";
    else
        pszAccess = "r";
    
    hSHP = SHPOpen ( CPLResetExtension( pszFullName, "shp" ) , pszAccess );
    hDBF = DBFOpen ( CPLResetExtension( pszFullName, "dbf" ) , pszAccess );
    
    CPLPopErrorHandler();
    
    if( NULL == hSHP || NULL == hDBF )
    {
        CPLString osMsg(CPLGetLastErrorMsg());
        CPLError( CE_Failure, CPLE_OpenFailed, "%s", osMsg.c_str() );

        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Update total shape count.                                       */
/* -------------------------------------------------------------------- */
    nTotalShapeCount = hDBF->nRecords;

    return OGRERR_NONE;
}
Exemple #25
0
int main(int argc, char **argv)
{
  if (argc == 1) { printf("usage: shapefile_to_kml [FILENAME]\n"); exit(1); }
  
  DBFHandle d = DBFOpen(argv[1], "rb");
  if (d == NULL) { printf("DBFOpen error (%s.dbf)\n", argv[1]); exit(1); }
	
	SHPHandle h = SHPOpen(argv[1], "rb");
  if (h == NULL) { printf("SHPOpen error (%s.dbf)\n", argv[1]); exit(1); }
	
  char filename[60];
  sprintf(filename, "%s.kml", argv[1]);
  printf("%s\n", filename);
  FILE *fp = fopen(filename, "w");
  if (fp == NULL) { printf("fopen error\n"); exit(1); }
	
  int nRecordCount = DBFGetRecordCount(d);
  int nFieldCount = DBFGetFieldCount(d);
  printf("DBF has %d records (with %d fields)\n", nRecordCount, nFieldCount);
	
  fprintf(fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  fprintf(fp, "<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n");

  /*for (int i = 0 ; i < nFieldCount ; i++)
  {
    char pszFieldName[12];
    int pnWidth;
    int pnDecimals;
    DBFFieldType ft = DBFGetFieldInfo(d, i, pszFieldName, &pnWidth, &pnDecimals);
    switch (ft)
    {
      case FTString:
        fprintf(fp, ", %s VARCHAR(%d)", pszFieldName, pnWidth);
        break;
      case FTInteger:
        fprintf(fp, ", %s INT", pszFieldName);
        break;
      case FTDouble:
        fprintf(fp, ", %s FLOAT(15,10)", pszFieldName);
        break;
      case FTLogical:
        break;
      case FTInvalid:
        break;
    }
  }*/
  
  fprintf(fp, "  <Document>\n");
  int i;
  for (i = 0 ; i < nRecordCount ; i++)
  {
    fprintf(fp, "    <Placemark>\n");
    fprintf(fp, "      <name>%s</name>\n", (char *)DBFReadStringAttribute(d, i, 2));
    fprintf(fp, "      <Polygon>\n");
    fprintf(fp, "        <extrude>1</extrude>\n");
    fprintf(fp, "        <altitudeMode>relativeToGround</altitudeMode>\n");
    fprintf(fp, "        <outerBoundaryIs>\n");
    fprintf(fp, "          <LinearRing>\n");
    fprintf(fp, "            <coordinates>\n");
    
    SHPObject	*psShape = SHPReadObject(h, i);
    int j, iPart;
    for (j = 0, iPart = 1; j < psShape->nVertices; j++)
    {
      fprintf(fp, "%f,%f,100\n", psShape->padfX[j], psShape->padfY[j]);
    }
    
    fprintf(fp, "            </coordinates>\n");
    fprintf(fp, "          </LinearRing>\n");
    fprintf(fp, "        </outerBoundaryIs>\n");
    fprintf(fp, "      </Polygon>\n");
    fprintf(fp, "    </Placemark>\n");
  }
  fprintf(fp, "  </Document>\n");
	
  /*int nShapeType;
  int nEntities;
  const char *pszPlus;
  double adfMinBound[4], adfMaxBound[4];
	
  SHPGetInfo(h, &nEntities, &nShapeType, adfMinBound, adfMaxBound);
  printf("SHP has %d entities\n", nEntities);
  
  for (i = 0; i < nEntities; i++)
  {
    SHPObject	*psShape = SHPReadObject(h, i);
    
    //fprintf(fp, "INSERT INTO edges (id) VALUES (%d);\n", i+1);
    
    int j, iPart;
    for (j = 0, iPart = 1; j < psShape->nVertices; j++)
    {
      const char *pszPartType = "";
      
      if (j == 0 && psShape->nParts > 0) pszPartType = SHPPartTypeName(psShape->panPartType[0]);
      if (iPart < psShape->nParts && psShape->panPartStart[iPart] == j)
      {
        pszPartType = SHPPartTypeName(psShape->panPartType[iPart]);
        iPart++;
        pszPlus = "+";
      }
      else
        pszPlus = " ";
      
      //if (j%500==0)
      //  fprintf(fp, "%sINSERT INTO vertexes (edge_id, x, y) VALUES (", (j!=0 ? ");\n": ""));
      //else
      //  fprintf(fp, "),(");
      
      //fprintf(fp, "%d, %f, %f", i+1, psShape->padfX[j], psShape->padfY[j]);
    }
    //fprintf(fp, ");\n");
    
    SHPDestroyObject(psShape);
  }*/
  
  fprintf(fp, "</kml>\n");
	printf("all done\n");
  
  fclose(fp);
  
	if (h != NULL) SHPClose(h);
	if (d != NULL) DBFClose(d);
}
Exemple #26
0
static void WritePointShapefile( const char * pszShapefile,
                                 SDTSTransfer * poTransfer,
                                 const char * pszMODN )

{
    SDTSPointReader     *poPointReader;

/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed Pointgon reader.                */
/* -------------------------------------------------------------------- */
    poPointReader = (SDTSPointReader *) 
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );
    
    if( poPointReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

    poPointReader->Rewind();

/* -------------------------------------------------------------------- */
/*      Create the Shapefile.                                           */
/* -------------------------------------------------------------------- */
    SHPHandle   hSHP;

    hSHP = SHPCreate( pszShapefile, SHPT_POINT );
    if( hSHP == NULL )
    {
        fprintf( stderr, "Unable to create shapefile `%s'\n",
                 pszShapefile );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    int         nAreaField, nSDTSRecordField;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );
    nAreaField = DBFAddField( hDBF, "AreaId", FTString, 12, 0 );
    
    char  **papszModRefs = poPointReader->ScanModuleReferences();
    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs );
    CSLDestroy( papszModRefs );

/* ==================================================================== */
/*      Process all the line features in the module.                    */
/* ==================================================================== */
    SDTSRawPoint        *poRawPoint;
        
    while( (poRawPoint = poPointReader->GetNextPoint()) != NULL )
    {
        int             iShape;
        
/* -------------------------------------------------------------------- */
/*      Write out a shape with the vertices.                            */
/* -------------------------------------------------------------------- */
        SHPObject       *psShape;

        psShape = SHPCreateSimpleObject( SHPT_POINT, 1,
                                         &(poRawPoint->dfX),
                                         &(poRawPoint->dfY),
                                         &(poRawPoint->dfZ) );

        iShape = SHPWriteObject( hSHP, -1, psShape );

        SHPDestroyObject( psShape );

/* -------------------------------------------------------------------- */
/*      Write out the attributes.                                       */
/* -------------------------------------------------------------------- */
        char    szID[13];

        DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField,
                                  poRawPoint->oModId.nRecord );
        
        sprintf( szID, "%s:%ld",
                 poRawPoint->oAreaId.szModule,
                 poRawPoint->oAreaId.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nAreaField, szID );

        WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawPoint );

        if( !poPointReader->IsIndexed() )
            delete poRawPoint;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    SHPClose( hSHP );
}    
Exemple #27
0
void Builder::print_shpObjects()
{
  QgsDebugMsg( QString( "Number of primitives: %1" ).arg( shpObjects.size() ) );
  QgsDebugMsg( QString( "Number of text fields: %1" ).arg( textObjects.size() ) );
  QgsDebugMsg( QString( "Number of inserts fields: %1" ).arg( insertObjects.size() ) );

  SHPHandle hSHP;

  if ( fname.endsWith( ".shp", Qt::CaseInsensitive ) )
  {
    QString fn( fname.mid( fname.length() - 4 ) );

    outputdbf = fn + ".dbf";
    outputshp = fn + ".shp";
    outputtdbf = fn + "_texts.dbf";
    outputtshp = fn + "_texts.shp";
    outputidbf = fn + "_inserts.dbf";
    outputishp = fn + "_inserts.shp";
  }
  else
  {
    outputdbf = outputtdbf = outputidbf = fname + ".dbf";
    outputshp = outputtshp = outputishp = fname + ".shp";
  }

  DBFHandle dbffile = DBFCreate( outputdbf.toUtf8() );
  DBFAddField( dbffile, "myid", FTInteger, 10, 0 );

  hSHP = SHPCreate( outputshp.toUtf8(), shapefileType );

  QgsDebugMsg( "Writing to main shp file..." );

  for ( int i = 0; i < shpObjects.size(); i++ )
  {
    SHPWriteObject( hSHP, -1, shpObjects[i] );
    SHPDestroyObject( shpObjects[i] );
    DBFWriteIntegerAttribute( dbffile, i, 0, i );
  }

  SHPClose( hSHP );
  DBFClose( dbffile );

  QgsDebugMsg( "Done!" );

  if ( !textObjects.isEmpty() )
  {
    SHPHandle thSHP;

    DBFHandle Tdbffile = DBFCreate( outputtdbf.toUtf8() );
    thSHP = SHPCreate( outputtshp.toUtf8(), SHPT_POINT );

    DBFAddField( Tdbffile, "tipx", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tipy", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tipz", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tapx", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tapy", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tapz", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "height", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "scale", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "flags", FTInteger, 10, 0 );
    DBFAddField( Tdbffile, "hjust", FTInteger, 10, 0 );
    DBFAddField( Tdbffile, "vjust", FTInteger, 10, 0 );
    DBFAddField( Tdbffile, "text", FTString, 50, 0 );
    DBFAddField( Tdbffile, "style", FTString, 50, 0 );
    DBFAddField( Tdbffile, "angle", FTDouble, 20, 10 );

    QgsDebugMsg( "Writing Texts' shp File..." );

    for ( int i = 0; i < textObjects.size(); i++ )
    {
      SHPObject *psObject;
      double x = textObjects[i].ipx;
      double y = textObjects[i].ipy;
      double z = textObjects[i].ipz;
      psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL );

      SHPWriteObject( thSHP, -1, psObject );

      DBFWriteDoubleAttribute( Tdbffile, i, 0, textObjects[i].ipx );
      DBFWriteDoubleAttribute( Tdbffile, i, 1, textObjects[i].ipy );
      DBFWriteDoubleAttribute( Tdbffile, i, 2, textObjects[i].ipz );

      DBFWriteDoubleAttribute( Tdbffile, i, 3, textObjects[i].apx );
      DBFWriteDoubleAttribute( Tdbffile, i, 4, textObjects[i].apy );
      DBFWriteDoubleAttribute( Tdbffile, i, 5, textObjects[i].apz );

      DBFWriteDoubleAttribute( Tdbffile, i, 6, textObjects[i].height );
      DBFWriteDoubleAttribute( Tdbffile, i, 7, textObjects[i].xScaleFactor );
      DBFWriteIntegerAttribute( Tdbffile, i, 8, textObjects[i].textGenerationFlags );

      DBFWriteIntegerAttribute( Tdbffile, i, 9, textObjects[i].hJustification );
      DBFWriteIntegerAttribute( Tdbffile, i, 10, textObjects[i].vJustification );

      DBFWriteStringAttribute( Tdbffile, i, 11, textObjects[i].text.c_str() );
      DBFWriteStringAttribute( Tdbffile, i, 12, textObjects[i].style.c_str() );

      DBFWriteDoubleAttribute( Tdbffile, i, 13, textObjects[i].angle );

      SHPDestroyObject( psObject );
    }
    SHPClose( thSHP );
    DBFClose( Tdbffile );

    QgsDebugMsg( "Done!" );
  }

  if ( !insertObjects.isEmpty() )
  {
    SHPHandle ihSHP;

    DBFHandle Idbffile = DBFCreate( outputidbf.toUtf8() );
    ihSHP = SHPCreate( outputishp.toUtf8(), SHPT_POINT );

    DBFAddField( Idbffile, "name", FTString, 200, 0 );
    DBFAddField( Idbffile, "ipx", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "ipy", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "ipz", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "sx", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "sy", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "sz", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "angle", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "cols", FTInteger, 20, 0 );
    DBFAddField( Idbffile, "rows", FTInteger, 20, 0 );
    DBFAddField( Idbffile, "colsp", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "rowsp", FTDouble, 20, 10 );

    QgsDebugMsg( "Writing Insert' shp File..." );

    for ( int i = 0; i < insertObjects.size(); i++ )
    {
      SHPObject *psObject;
      double &x = insertObjects[i].ipx;
      double &y = insertObjects[i].ipy;
      double &z = insertObjects[i].ipz;
      psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL );

      SHPWriteObject( ihSHP, -1, psObject );

      int c = 0;
      DBFWriteStringAttribute( Idbffile, i, c++, insertObjects[i].name.c_str() );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipx );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipy );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipz );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sx );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sy );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sz );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].angle );
      DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects[i].cols );
      DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects[i].rows );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].colSp );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].rowSp );

      SHPDestroyObject( psObject );
    }
    SHPClose( ihSHP );
    DBFClose( Idbffile );

    QgsDebugMsg( "Done!" );
  }
}
Exemple #28
0
int main( int argc, char ** argv )

{
    DBFHandle	hDBF;
    int		*panWidth, i, iRecord;
    char	szFormat[32], szField[1024];
    char	ftype[15], cTitle[32], nTitle[32];
    int		nWidth, nDecimals;
    int		cnWidth, cnDecimals;
    DBFHandle	cDBF;
    DBFFieldType	hType,cType;
    int		ci, ciRecord;

/* -------------------------------------------------------------------- */
/*      Display a usage message.                                        */
/* -------------------------------------------------------------------- */
    if( argc != 2 )
    {
	printf( "dbfinfo xbase_file\n" );
	exit( 1 );
    }

/* -------------------------------------------------------------------- */
/*      Open the file.                                                  */
/* -------------------------------------------------------------------- */
    hDBF = DBFOpen( argv[1], "rb" );
    if( hDBF == NULL )
    {
	printf( "DBFOpen(%s,\"r\") failed.\n", argv[1] );
	exit( 2 );
    }

    printf ("Info for %s\n",argv[1]);

/* -------------------------------------------------------------------- */
/*	If there is no data in this file let the user know.		*/
/* -------------------------------------------------------------------- */
    i = DBFGetFieldCount(hDBF);
    printf ("%ld Columns,  %ld Records in file\n",i,DBFGetRecordCount(hDBF));
    
/* -------------------------------------------------------------------- */
/*	Compute offsets to use when printing each of the field 		*/
/*	values. We make each field as wide as the field title+1, or 	*/
/*	the field value + 1. 						*/
/* -------------------------------------------------------------------- */
    panWidth = (int *) malloc( DBFGetFieldCount( hDBF ) * sizeof(int) );

    for( i = 0; i < DBFGetFieldCount(hDBF); i++ )
    {
	char		szTitle[12];
	DBFFieldType	eType;

	switch ( DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals )) {
	      case FTString:
	        strcpy (ftype, "string");;
		break;

	      case FTInteger:
	    	strcpy (ftype, "integer");
		break;

	      case FTDouble:
	    	strcpy (ftype, "float");
		break;
		
	      case FTInvalid:
	    	strcpy (ftype, "invalid/unsupported");
		break;
		
	      default:
	      	strcpy (ftype, "unknown");
	      	break;			
	    }
        printf ("%15.15s\t%15s  (%d,%d)\n",szTitle, ftype, nWidth, nDecimals);

    }

    DBFClose( hDBF );

    return( 0 );
}
Exemple #29
0
static void WriteAttributeDBF( const char * pszShapefile,
                               SDTSTransfer * poTransfer,
                               const char * pszMODN )

{
    SDTSAttrReader      *poAttrReader;

/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed Pointgon reader.                */
/* -------------------------------------------------------------------- */
    poAttrReader = (SDTSAttrReader *) 
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );
    
    if( poAttrReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

    poAttrReader->Rewind();

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );

/* -------------------------------------------------------------------- */
/*      Prepare the schema.                                             */
/* -------------------------------------------------------------------- */
    char        **papszMODNList = CSLAddString( NULL, pszMODN );

    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszMODNList );

    CSLDestroy( papszMODNList );
    
/* ==================================================================== */
/*      Process all the records in the module.                          */
/* ==================================================================== */
    SDTSAttrRecord *poRecord;
    int         iRecord = 0;

    while((poRecord = (SDTSAttrRecord*)poAttrReader->GetNextFeature()) != NULL)
    {
        DBFWriteIntegerAttribute( hDBF, iRecord, 0,
                                  poRecord->oModId.nRecord );

        WriteAttrRecordToDBF( hDBF, iRecord, poTransfer, poRecord->poATTR );

        if( !poAttrReader->IsIndexed() )
            delete poRecord;
        
        iRecord++;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
}    
Exemple #30
0
static void WritePolygonShapefile( const char * pszShapefile,
                                   SDTSTransfer * poTransfer, 
                                   const char * pszMODN )

{
    SDTSPolygonReader *poPolyReader;

/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed polygon reader.                */
/* -------------------------------------------------------------------- */
    poPolyReader = (SDTSPolygonReader *) 
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );
    
    if( poPolyReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Assemble polygon geometries from all the line layers.           */
/* -------------------------------------------------------------------- */
    poPolyReader->AssembleRings( poTransfer, poTransfer->FindLayer(pszMODN) );
    
/* -------------------------------------------------------------------- */
/*      Create the Shapefile.                                           */
/* -------------------------------------------------------------------- */
    SHPHandle   hSHP;

    hSHP = SHPCreate( pszShapefile, SHPT_POLYGON );
    if( hSHP == NULL )
    {
        fprintf( stderr, "Unable to create shapefile `%s'\n",
                 pszShapefile );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    int         nSDTSRecordField;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );

    char  **papszModRefs = poPolyReader->ScanModuleReferences();
    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs );
    CSLDestroy( papszModRefs );

/* ==================================================================== */
/*      Process all the polygon features in the module.                 */
/* ==================================================================== */
    SDTSRawPolygon      *poRawPoly;

    poPolyReader->Rewind();
    while( (poRawPoly = (SDTSRawPolygon *) poPolyReader->GetNextFeature())
           != NULL )
    {
        int             iShape;

/* -------------------------------------------------------------------- */
/*      Write out a shape with the vertices.                            */
/* -------------------------------------------------------------------- */
        SHPObject       *psShape;

        psShape = SHPCreateObject( SHPT_POLYGON, -1, poRawPoly->nRings,
                                   poRawPoly->panRingStart, NULL,
                                   poRawPoly->nVertices,
                                   poRawPoly->padfX, 
                                   poRawPoly->padfY, 
                                   poRawPoly->padfZ,
                                   NULL );

        iShape = SHPWriteObject( hSHP, -1, psShape );

        SHPDestroyObject( psShape );

/* -------------------------------------------------------------------- */
/*      Write out the attributes.                                       */
/* -------------------------------------------------------------------- */
        DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField,
                                  poRawPoly->oModId.nRecord );
        WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawPoly );

        if( !poPolyReader->IsIndexed() )
            delete poRawPoly;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    SHPClose( hSHP );
}