Example #1
0
///////////////////////////////////////////////////////////////////////////////
// Eine Shapedatei öffnen
HRESULT CShapeDataSource::OpenFile(const char *pszNewName, bool fUpdate, bool fTestOpen)
{
	_ASSERTE(NULL != pszNewName);
	if (NULL == pszNewName)
		return E_POINTER;

SHPHandle hSHP = NULL;
DBFHandle hDBF = NULL;

	if (fUpdate)
		hSHP = SHPOpen (pszNewName, "r+");
	else
		hSHP = SHPOpen (pszNewName, "r");
	if (NULL == hSHP)
		return S_FALSE;
	
// Open the .dbf file, if it exists.
	if (fUpdate)
		hDBF = DBFOpen (pszNewName, "rb+");
	else
		hDBF = DBFOpen (pszNewName, "rb");

// Extract the basename of the file.
	COM_TRY {
	// Create the layer object and add layer to data source layer list.
	os_path path (pszNewName);

		m_Layers.push_back (new CShapeLayer(path.base().c_str(), hSHP, hDBF, fUpdate));

	} COM_CATCH;
	return S_OK;
}
// ---------------------------------------------------------------------------
// Constructeur
// ------------
bDBFTable	::bDBFTable(	const char* path,
							const char* name,
							bool create, 
							double* reso,
							double* ox,
							double* oy,
							int* tsrid,
							int* asrid,
							int* status)
				:bStdTable(*reso,*ox,*oy,*tsrid,*asrid,status){
_bTrace_("bDBFTable::bDBFTable",false);

char	fpath[1024];
	
	sprintf(fpath,"%s%s",path,name);
	_dbf=DBFOpen(fpath,"rb+");
	if(!_dbf){
		_dbf=DBFOpen(fpath,"rb");	
	}
	if(_dbf){
		return;
	}
	if(!create){
		*status=-1;
_te_("table not found : "+fpath);
		return;
	}
	_dbf=DBFCreate(fpath);
	if(!_dbf){
_te_("creation failed for : "+fpath);
		*status=-1;
		return;
	}
	*status=0;
}
Example #3
0
File: shape.c Project: peko/tttm2
// 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 );
}
Example #4
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);
    }
Example #5
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 );
}
Example #6
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;
}
Example #7
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;
}
Example #8
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 );
}
Example #9
0
//  Function to read outlets from a shapefile - overloaded to return an array of integer ID's
int readoutlets(char *outletsfile, int *noutlets, double*& x, double*& y, int*& id)
{
	SHPHandle shp = SHPOpen(outletsfile, "rb");
	char dbffile[MAXLN];
	nameadd(dbffile, outletsfile, ".dbf");
	DBFHandle dbf = DBFOpen(dbffile, "rb");
	if ((shp != NULL) && (dbf != NULL)) {
		int nEntities = 0;
		int nShapeType = 0;
		SHPGetInfo(shp, &nEntities, &nShapeType, NULL, NULL );
		if (nShapeType != SHPT_POINT)
		{
			fprintf(stderr, "Outlets shapefile %s is not a point shapefile\n", outletsfile);
			fflush(stderr);
			return 1;
		}
	long p_size;
	long countPts = 0;

	int nfld = DBFGetFieldCount(dbf);
	//int idfld = DBFGetFieldIndex(dbf, "id");
	int idfld = DBFGetFieldIndex(dbf, "OBJECTID"); // ZhuLJ, 2015/6/16
	for( int i=0; i<nEntities; i++) {
		SHPObject * shape = SHPReadObject(shp, i);
		countPts += shape->nVertices;
		SHPDestroyObject(shape);
	}
	x = new double[countPts];
	y = new double[countPts];
	if (idfld >= 0)
		id = new int[countPts];
    int nxy=0;
	for( int i=0; i<nEntities; i++) {
		SHPObject * shape = SHPReadObject(shp, i);
		p_size = shape->nVertices;
		for( int j=0; j<p_size; j++) {
			x[nxy] = shape->padfX[j];
			y[nxy] = shape->padfY[j];
			if (idfld >= 0)
			{
				id[nxy] = DBFReadIntegerAttribute(dbf, i, idfld);
			}
			nxy++;
		}
		SHPDestroyObject(shape);
	}
	*noutlets=nxy;
	SHPClose(shp);
	return 0;
	}
	else { 
		fprintf(stderr, "Error opening outlets shapefile: %s\n", outletsfile);
		fflush(stderr);
		return 1;
	}	
}
Example #10
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;
}
Example #11
0
bool rspfShapeDatabase::open(const rspfFilename& file,
                             const rspfString& flags)
{
    if(isOpen()) close();
    theHandle = DBFOpen(file.c_str(), flags.c_str());
    if(theHandle)
    {
        theFilename = file;
        theRecordNumber = -1;
    }
    return (theHandle != NULL);
}
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);
}
Example #13
0
void surfaceVectorField::OpenShape()
{
/*
	FILE *fx=fopen(ShapeFileName, "w");
     if(fx)
	     fclose(fx);
	fx=fopen(DataBaseName, "w");
     if(fx)
	     fclose(fx);
*/
     hSHP=SHPOpen(ShapeFileName.c_str(), "rb+");
     hDBF=DBFOpen(DataBaseName.c_str(), "rb+");
}
Example #14
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;
}
Example #15
0
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
}
Example #16
0
void CDbfFile::Initialize()
{
	if(_bInit) 
	{
		DBFSetColumn(&_psDBFAttList);
		ValidateDBF();
		_bInit = false;
		
	}
	hDBF = DBFOpen("r+b" );
	if( hDBF == NULL )
	{
		printf("DBFOpen failed: %s\n", _szDBFName);
		exit(1);
	}

}
Example #17
0
void open_baseline_shape(char *inFile, DBFHandle *dbase, SHPHandle *shape)
{
    char *dbaseFile;

    // Open database for adding values
    dbaseFile = (char *) MALLOC(sizeof(char)*(strlen(inFile)+5));
    sprintf(dbaseFile, "%s.dbf", inFile);
    *dbase = DBFOpen(dbaseFile, "r+b");
    if (*dbase == NULL)
        asfPrintError("Could not open database file '%s'\n", dbaseFile);

    // Open shapefile for adding values
    *shape = SHPOpen(inFile, "r+b");
    if (*shape == NULL)
        asfPrintError("Could not open shapefile '%s\n", inFile);

    FREE(dbaseFile);

    return;
}
Example #18
0
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);
}
Example #19
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;
}
Example #20
0
File: shape.c Project: peko/tttm2
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;
}
Example #21
0
int load_table_head(int t)
{
    int i, ncol, dtype, type, width, decimals;
    DBFHandle dbf;
    char fname[20];

    G_debug(2, "load_table_head(): tab = %d, %s", t, db.tables[t].file);

    if (db.tables[t].described == TRUE)	/*already described */
        return DB_OK;

    if (access(db.tables[t].file, R_OK) == 0)
        db.tables[t].read = TRUE;
    else
        db.tables[t].read = FALSE;

    if (access(db.tables[t].file, W_OK) == 0)
        db.tables[t].write = TRUE;
    else
        db.tables[t].write = FALSE;

    /* load */
    dbf = DBFOpen(db.tables[t].file, "r");
    if (dbf == NULL) {
        append_error("Cannot open dbf file.\n");
        return DB_FAILED;
    }

    ncol = DBFGetFieldCount(dbf);
    G_debug(2, "  ncols = %d", ncol);

    for (i = 0; i < ncol; i++) {
        dtype = DBFGetFieldInfo(dbf, i, fname, &width, &decimals);
        G_debug(2, "  DBFFieldType %d", dtype);

        switch (dtype) {
        case FTString:
            type = DBF_CHAR;
            break;
        case FTInteger:
            type = DBF_INT;
            break;
        case FTDouble:
            type = DBF_DOUBLE;
            break;
        case FTInvalid:
            G_warning("invalid/unsupported DBFFieldType");
            break;
        default:
            G_warning("unknown DBFFieldType");
            break;
        }

        add_column(t, type, fname, width, decimals);
    }

    DBFClose(dbf);
    db.tables[t].described = TRUE;

    return DB_OK;
}
Example #22
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;
}
Example #23
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);
}
Example #24
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 );
}
Example #25
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 );
}
Example #26
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");
}
Example #27
0
bool writeAdminRegionsToDatabase(QString const &a0_dbf,
                                 QString const &a1_dbf,
                                 Kompex::SQLiteStatement * pStmt)
{
    // because shapefiles are evil
    QTextCodec * codec = QTextCodec::codecForName("windows-1252");

    // populate the admin0 temp table
    {
        DBFHandle a0_hDBF = DBFOpen(a0_dbf.toLocal8Bit().data(),"rb");
        if(a0_hDBF == NULL)   {
            qDebug() << "ERROR: Could not open admin0 dbf file";
            return -1;
        }

        size_t a0_numRecords = DBFGetRecordCount(a0_hDBF);
        if(a0_numRecords == 0)   {
            qDebug() << "ERROR: admin0 dbf file has no records!";
            return -1;
        }

        size_t a0_idx_adm_name  = DBFGetFieldIndex(a0_hDBF,"name");
        size_t a0_idx_adm_a3    = DBFGetFieldIndex(a0_hDBF,"adm0_a3");
        size_t a0_idx_sov_name  = DBFGetFieldIndex(a0_hDBF,"sovereignt");
        size_t a0_idx_sov_a3    = DBFGetFieldIndex(a0_hDBF,"sov_a3");
        size_t a0_idx_type      = DBFGetFieldIndex(a0_hDBF,"type");
        size_t a0_idx_note      = DBFGetFieldIndex(a0_hDBF,"note_adm0");

        // create a temporary table we can use to lookup
        // the admin0 data we want for each admin1 entry
        pStmt->SqlStatement("CREATE TABLE IF NOT EXISTS temp("
                            "id INTEGER PRIMARY KEY NOT NULL UNIQUE,"
                            "adm_a3 TEXT NOT NULL UNIQUE,"
                            "sov_a3 TEXT NOT NULL,"
                            "adm_name TEXT,"
                            "sov_name TEXT,"
                            "type TEXT,"
                            "note TEXT);");

        pStmt->BeginTransaction();
        for(size_t i=0; i < a0_numRecords; i++)   {
            QString s0 = QString::number(i,10);
            QString s1(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_adm_a3)));
            QString s2(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_sov_a3)));
            QString s3(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_adm_name)));
            QString s4(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_sov_name)));
            QString s5(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_type)));
            QString s6(codec->toUnicode(DBFReadStringAttribute(a0_hDBF, i, a0_idx_note)));

            QString stmt("INSERT INTO temp("
                         "id,"
                         "adm_a3,"
                         "sov_a3,"
                         "adm_name,"
                         "sov_name,"
                         "type,"
                         "note) VALUES(" +
                         s0 + "," +
                         "\"" + s1 + "\","
                         "\"" + s2 + "\","
                         "\"" + s3 + "\","
                         "\"" + s4 + "\","
                         "\"" + s5 + "\","
                         "\"" + s6 + "\");");

            pStmt->SqlStatement(stmt.toStdString());
        }
        pStmt->CommitTransaction();
        DBFClose(a0_hDBF);
    }

    // populate the admin1 table
    {
        DBFHandle a1_hDBF = DBFOpen(a1_dbf.toLocal8Bit().data(),"rb");
        if(a1_hDBF == NULL)   {
            qDebug() << "ERROR: Could not open admin1 dbf file";
            return false;
        }

        size_t a1_numRecords = DBFGetRecordCount(a1_hDBF);
        if(a1_numRecords == 0)   {
            qDebug() << "ERROR: admin1 dbf file has no records!";
            return false;
        }

        // open admin1 translation csv if it exists
        QStringList listAdmin1Subs;
        QString pathSubs = a1_dbf;
        pathSubs.chop(4);
        pathSubs.append("_translations.dat");
        bool admin1_csv_sub = getAdmin1TranslationSubs(pathSubs,listAdmin1Subs);
        if(admin1_csv_sub)   {
            if(listAdmin1Subs.size() == a1_numRecords)   {
                qDebug() << "INFO: Using translation substitute file: "<< pathSubs;
            }
            else   {
                qDebug() << "WARN: Translation file has wrong number "
                         "of entries: " << listAdmin1Subs.size();
                admin1_csv_sub = false;
            }
        }

        size_t a1_idx_adm_name  = DBFGetFieldIndex(a1_hDBF,"name");
        size_t a1_idx_adm_a3    = DBFGetFieldIndex(a1_hDBF,"sr_adm0_a3");
        size_t a1_idx_sov_a3    = DBFGetFieldIndex(a1_hDBF,"sr_sov_a3");
        size_t a1_idx_fclass    = DBFGetFieldIndex(a1_hDBF,"featurecla");
        size_t a1_idx_adminname = DBFGetFieldIndex(a1_hDBF,"admin");

        QStringList listSqlSaveSov;
        QStringList listSqlSaveAdmin0;
        QStringList listSqlSaveAdmin1;

        for(size_t i=0; i < a1_numRecords; i++)   {
            // get the name of this admin1 entry
            QString admin1_idx = QString::number(i,10);
            QString admin1_name(codec->toUnicode(DBFReadStringAttribute(a1_hDBF, i, a1_idx_adm_name)));

            // if the adm1 fclass is an aggregation, minor island or
            // remainder, we grab the name from another field which
            // doesn't contain a bunch of additional metadata
            QString fclass(codec->toUnicode(DBFReadStringAttribute(a1_hDBF, i, a1_idx_fclass)));
            if(fclass.contains("aggregation") ||
                    fclass.contains("minor island") ||
                    fclass.contains("remainder"))
            {
                admin1_name = QString(codec->toUnicode(DBFReadStringAttribute(
                        a1_hDBF, i, a1_idx_adminname)));
            }
            else   {
                // if there's no special feature class than we check
                // to see if there's a translation substitute available
                if(admin1_csv_sub && (listAdmin1Subs[i].size() > 0))   {
                    admin1_name = listAdmin1Subs[i];
                }
            }

            // get the adm_a3,sov_a3 code for this admin1 entry
            QString adm_a3(codec->toUnicode(DBFReadStringAttribute(a1_hDBF, i, a1_idx_adm_a3)));
            QString sov_a3(codec->toUnicode(DBFReadStringAttribute(a1_hDBF, i, a1_idx_sov_a3)));

            // check if the adm_a3 code exists in the temp database
            QString stmt("SELECT * FROM temp WHERE adm_a3=\""+ adm_a3 + "\";");
            pStmt->Sql(stmt.toStdString());

            if(pStmt->FetchRow())   {
                // save admin0 info
                QString admin0_idx  = QString::number(pStmt->GetColumnInt("id"),10);
                QString admin0_type = QString::fromStdString(pStmt->GetColumnString("type"));
                QString admin0_note = QString::fromStdString(pStmt->GetColumnString("note"));
                pStmt->FreeQuery();

                // save admin1 info; we currently derive the
                // disputed field from admin0 type and note fields
                QString admin1_disputed = "0";
                if(admin0_type.contains("Disputed") ||
                        admin0_note.contains("Disputed"))   {
                    admin1_disputed = "1";
                }

                stmt = QString("INSERT INTO admin1(id,name,disputed,admin0,sov) VALUES(" +
                               admin1_idx + ",\"" +
                               admin1_name + "\"," +
                               admin1_disputed + "," +
                               admin0_idx + "," +
                               admin0_idx + ");");
                listSqlSaveAdmin1.push_back(stmt);
            }
            else   {
                pStmt->FreeQuery();

                // if there isn't a matching adm_a3 code in the temp
                // database try to get the sovereign state instead
                stmt = QString("SELECT * FROM temp WHERE sov_a3=\""+ sov_a3 + "\";");
                pStmt->Sql(stmt.toStdString());

                if(pStmt->FetchRow())   {
                    QString sov_idx     = QString::number(pStmt->GetColumnInt("id"));
                    pStmt->FreeQuery();

                    // since there's no true corresponding entry for
                    // the admin1 region through the adm_a3 code, we
                    // can't test for disputed regions
                    QString admin1_disputed = "0";

                    // to indicate that no admin0 region data exists
                    // for this entry, we use an index of value -1
                    QString admin0_idx = "-1";

                    stmt = QString("INSERT INTO admin1(id,name,disputed,admin0,sov) VALUES(" +
                                   admin1_idx + ",\"" +
                                   admin1_name + "\"," +
                                   admin1_disputed + "," +
                                   admin0_idx + "," +
                                   sov_idx + ");");
                    listSqlSaveAdmin1.push_back(stmt);
                }
                else   {
                    // fail without a matching adm_a3 or sov_a3
                    pStmt->FreeQuery();
                    return false;
                }
            }
        }

        // populate the admin0 and sov tables
        {
            QString stmt("SELECT * FROM temp;");
            pStmt->Sql(stmt.toStdString());

            while(pStmt->FetchRow())   {
                QString idx         = QString::number(pStmt->GetColumnInt("id"),10);
                QString admin0_name = QString::fromStdString(pStmt->GetColumnString("adm_name"));
                QString sov_name    = QString::fromStdString(pStmt->GetColumnString("sov_name"));

                stmt = QString("INSERT INTO sov(id,name) VALUES("+
                               idx + ",\"" +
                               sov_name + "\");");
                listSqlSaveSov.push_back(stmt);

                stmt = QString("INSERT INTO admin0(id,name) VALUES("+
                               idx + ",\"" +
                               admin0_name + "\");");
                listSqlSaveAdmin0.push_back(stmt);
            }
            pStmt->FreeQuery();
        }

        // write prepared statements
        pStmt->BeginTransaction();
        for(int i=0; i < listSqlSaveSov.size(); i++)   {
            pStmt->SqlStatement(listSqlSaveSov[i].toUtf8().data());
        }
        pStmt->CommitTransaction();

        pStmt->BeginTransaction();
        for(int i=0; i < listSqlSaveAdmin0.size(); i++)   {
            pStmt->SqlStatement(listSqlSaveAdmin0[i].toUtf8().data());
        }
        pStmt->CommitTransaction();

        pStmt->BeginTransaction();
        for(int i=0; i < listSqlSaveAdmin1.size(); i++)   {
            pStmt->SqlStatement(listSqlSaveAdmin1[i].toUtf8().data());
        }
        pStmt->CommitTransaction();
    }

    // delete temp table
    pStmt->SqlStatement("DROP TABLE temp;");

    return true;
}
Example #28
0
//----------------------------------------------------------------------------
int ShapefileReader::RequestData(
                                 vtkInformation* vtkNotUsed( request ),
                                 vtkInformationVector** vtkNotUsed(inputVector),
                                 vtkInformationVector* outputVector)
{
  vtkInformation* outInfo = outputVector->GetInformationObject(0);
  vtkPolyData* polydata = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));

  if (illegalFileName()){
    return 0;
  }

  if (incompleteSrcFiles()){
    return 0;
  }

  SHPHandle shpHandle = SHPOpen(this->FileName, "rb");
  int fileType = 0;

  if (shpHandle == NULL){
    vtkErrorMacro("shp file read failed.");
    return 0;
  }

  vtkDebugMacro("file type: " << shpHandle->nShapeType);

  switch (shpHandle->nShapeType) {
    case SHPT_NULL:
      vtkErrorMacro("NULL Object type." << this->FileName);
      SHPClose(shpHandle);
      return 0;
      break;
    case SHPT_POINT:
    case SHPT_POINTZ:
    case SHPT_POINTM:
    case SHPT_MULTIPOINT:
    case SHPT_MULTIPOINTZ:
    case SHPT_MULTIPOINTM:
      fileType = POINTOBJ;
      break;
    case SHPT_ARC:
    case SHPT_ARCZ:
    case SHPT_ARCM:
      fileType = LINEOBJ;
      break;
    case SHPT_POLYGON:
    case SHPT_POLYGONZ:
    case SHPT_POLYGONM:
      fileType = FACEOBJ;
      break;
    case SHPT_MULTIPATCH:
      fileType = MESHOBJ;
      break;
    default:
      vtkErrorMacro("Unknown Object type." << this->FileName);
      SHPClose(shpHandle);
      return 0;
  }

  int pCount=0, pStart=0, pEnd=0;
  int vTracker = 0, pid=0;
  SHPObject* shpObj;

  vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New();
  vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkCellArray> strips = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkCellArray> pLines = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkCellArray> verts = vtkSmartPointer<vtkCellArray>::New();
  vtkSmartPointer<vtkTriangleFilter> tFilter = vtkSmartPointer<vtkTriangleFilter>::New();
  vtkSmartPointer<vtkStripper> stripper = vtkSmartPointer<vtkStripper>::New();
  vtkSmartPointer<vtkPolyData> pdRaw = vtkSmartPointer<vtkPolyData>::New();
  vtkSmartPointer<vtkPolyData> pdRefined = vtkSmartPointer<vtkPolyData>::New();

  //looping through all records in file
  for (int rIndex = 0; rIndex < shpHandle->nRecords; rIndex++){
    
    shpObj = SHPReadObject(shpHandle, rIndex);

    //making sure shp object type is consistent with file type
    if (shpObj->nSHPType != shpHandle->nShapeType){
      vtkErrorMacro("Inconsistent shape type of record: " << rIndex 
        << " in file " << this->FileName);
      continue;
    }

    pCount = shpObj->nParts;
    
    switch (fileType){
    case POINTOBJ:{

      vtkIdType *ids = new vtkIdType[shpObj->nVertices];

      for (int vIndex = 0; vIndex < shpObj->nVertices; vIndex++){
        pts->InsertPoint(pid,shpObj->padfX[vIndex],
                             shpObj->padfY[vIndex],
                             shpObj->padfZ[vIndex]);
        ids[vIndex] = pid++;
      }
      verts->InsertNextCell(shpObj->nVertices, ids);
      delete ids;
      ids = NULL;
      break;

    }
    case LINEOBJ:{
      
      for (int pIndex = 0; pIndex < pCount; pIndex++){
        pStart = shpObj->panPartStart[pIndex];

        if (pIndex == (pCount-1)){
          pEnd = shpObj->nVertices;
        }else{
          pEnd = shpObj->panPartStart[pIndex+1];
        }

        vtkSmartPointer<vtkPolyLine> pLine = vtkSmartPointer<vtkPolyLine>::New();
        pLine->GetPointIds()->SetNumberOfIds(pEnd-pStart); 

        for (int vIndex = pStart; vIndex < pEnd; vIndex++){
          pts->InsertNextPoint(shpObj->padfX[vIndex],
                               shpObj->padfY[vIndex],
                               shpObj->padfZ[vIndex]);
          pLine->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
        }
        pLines->InsertNextCell(pLine);
        vTracker += pEnd-pStart;
      }
      break;

    }
    case FACEOBJ:{

      for (int pIndex = 0; pIndex < pCount; pIndex++){
        pStart = shpObj->panPartStart[pIndex];

        if (pIndex == (pCount-1)){
          pEnd = shpObj->nVertices;
        }else{
          pEnd = shpObj->panPartStart[pIndex+1];
        }
        vtkSmartPointer<vtkPolygon> poly = vtkSmartPointer<vtkPolygon>::New();
        vtkSmartPointer<vtkPolyLine> pLine = vtkSmartPointer<vtkPolyLine>::New();
        poly->GetPointIds()->SetNumberOfIds(pEnd-pStart); 
        pLine->GetPointIds()->SetNumberOfIds(pEnd-pStart); 

        for (int vIndex = pStart; vIndex < pEnd; vIndex++){
          pts->InsertNextPoint(shpObj->padfX[vIndex],
                               shpObj->padfY[vIndex],
                               shpObj->padfZ[vIndex]);
          poly->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
          pLine->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
        }

        polys->InsertNextCell(poly);
        pLines->InsertNextCell(pLine);
        vTracker += pEnd-pStart;
      }
      break;

    }
    case MESHOBJ:{

      switch (*(shpObj->panPartType)){

      case SHPP_TRISTRIP:{
        for (int pIndex = 0; pIndex < pCount; pIndex++){
          pStart = shpObj->panPartStart[pIndex];

          if (pIndex == (pCount-1)){
            pEnd = shpObj->nVertices;
          }else{
            pEnd = shpObj->panPartStart[pIndex+1];
          }

          vtkSmartPointer<vtkTriangleStrip> strip = vtkSmartPointer<vtkTriangleStrip>::New();
          strip->GetPointIds()->SetNumberOfIds(pEnd-pStart);

          for (int vIndex = pStart; vIndex < pEnd; vIndex++){
            pts->InsertNextPoint(shpObj->padfX[vIndex],
                                 shpObj->padfY[vIndex],
                                 shpObj->padfZ[vIndex]);
            strip->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
          }

          strips->InsertNextCell(strip);
          vTracker += pEnd-pStart;
        }
        break;
      }//SHPP_TRISTRIP
      case SHPP_TRIFAN:{
        for (int pIndex = 0; pIndex < pCount; pIndex++){
          pStart = shpObj->panPartStart[pIndex];

          if (pIndex == (pCount-1)){
            pEnd = shpObj->nVertices;
          }else{
            pEnd = shpObj->panPartStart[pIndex+1];
          }

          vtkSmartPointer<vtkTriangleStrip> strip = vtkSmartPointer<vtkTriangleStrip>::New();
          strip->GetPointIds()->SetNumberOfIds(pEnd-pStart);

          for (int vIndex = pStart; vIndex < pEnd; vIndex++){
            pts->InsertNextPoint(shpObj->padfX[vIndex],
                                 shpObj->padfY[vIndex],
                                 shpObj->padfZ[vIndex]);
            strip->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
          }

          strips->InsertNextCell(strip);
          vTracker += pEnd-pStart;
        }
        break;
      }//SHPP_TRIFAN
      case SHPP_OUTERRING:
      case SHPP_INNERRING:
      case SHPP_FIRSTRING:
      case SHPP_RING:{
        for (int pIndex = 0; pIndex < pCount; pIndex++){
        pStart = shpObj->panPartStart[pIndex];

        if (pIndex == (pCount-1)){
          pEnd = shpObj->nVertices;
        }else{
          pEnd = shpObj->panPartStart[pIndex+1];
        }
        vtkSmartPointer<vtkPolygon> poly = vtkSmartPointer<vtkPolygon>::New();
        vtkSmartPointer<vtkPolyLine> pLine = vtkSmartPointer<vtkPolyLine>::New();
        poly->GetPointIds()->SetNumberOfIds(pEnd-pStart); 
        pLine->GetPointIds()->SetNumberOfIds(pEnd-pStart); 

        for (int vIndex = pStart; vIndex < pEnd; vIndex++){
          pts->InsertNextPoint(shpObj->padfX[vIndex],
                               shpObj->padfY[vIndex],
                               shpObj->padfZ[vIndex]);
          poly->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
          pLine->GetPointIds()->SetId(vIndex-pStart, vTracker+vIndex-pStart);
        }

        polys->InsertNextCell(poly);
        pLines->InsertNextCell(pLine);
        vTracker += pEnd-pStart;
      }
      break;
      }//rings
      }//panPartType
      break;
    
    }//MESHOBJ
    }//fileType

    SHPDestroyObject(shpObj);
  }// rIndex
  SHPClose(shpHandle);
  
  DBFHandle dbfHandle = DBFOpen(this->FileName, "rb");
  int fieldCount = DBFGetFieldCount(dbfHandle);
  
  for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++){
    
    DBFFieldType fieldType;
    const char *typeName;
    char nativeFieldType;
    char pszFieldName[12];
    int pnWidth=0, pnDecimals=0, recordCount=0;

    nativeFieldType = DBFGetNativeFieldType(dbfHandle, fieldIndex);
    fieldType = DBFGetFieldInfo(dbfHandle, fieldIndex, pszFieldName, &pnWidth, &pnDecimals);
    recordCount = DBFGetRecordCount(dbfHandle);

    vtkDebugMacro("record count: " << recordCount);

    switch (fieldType){
    case FTString:{

      vtkSmartPointer<vtkStringArray> cellData = vtkSmartPointer<vtkStringArray>::New();

      cellData->SetName(pszFieldName);
      
      for (int recordIndex = 0; recordIndex < recordCount; recordIndex++){
        if (DBFIsAttributeNULL(dbfHandle, recordIndex, fieldIndex)){
          cellData->InsertNextValue("NULL");
        }else{
          cellData->InsertNextValue(DBFReadStringAttribute(dbfHandle, recordIndex, fieldIndex));
        }
      }
      
      polydata->GetCellData()->AddArray(cellData);

      break;
    }
    case FTInteger:{

      vtkSmartPointer<vtkIntArray> cellData = vtkSmartPointer<vtkIntArray>::New();

      cellData->SetName(pszFieldName);
      
      for (int recordIndex = 0; recordIndex < recordCount; recordIndex++){
        if (DBFIsAttributeNULL(dbfHandle, recordIndex, fieldIndex)){
          cellData->InsertNextValue(0);
        }else{
          cellData->InsertNextValue(DBFReadIntegerAttribute(dbfHandle, recordIndex, fieldIndex));
        }
      }
      
      polydata->GetCellData()->AddArray(cellData);

      break;
    }
    case FTDouble:{

      vtkSmartPointer<vtkDoubleArray> cellData = vtkSmartPointer<vtkDoubleArray>::New();

      cellData->SetName(pszFieldName);
      
      for (int recordIndex = 0; recordIndex < recordCount; recordIndex++){
        if (DBFIsAttributeNULL(dbfHandle, recordIndex, fieldIndex)){
          cellData->InsertNextValue(0.0);
        }else{
          cellData->InsertNextValue(DBFReadDoubleAttribute(dbfHandle, recordIndex, fieldIndex));
        }
      }
      
      polydata->GetCellData()->AddArray(cellData);

      break;
    }
    case FTLogical:{
      //what is this? lack of sample data!
      break;
    }
    case FTInvalid:{
      vtkErrorMacro("Invalid DBF field type");
      break;
    }    
    }
  }

  DBFClose(dbfHandle);

  
  //pdRaw->SetPoints(pts);
  //pdRaw->SetPolys(polys);
  //pdRaw->SetLines(pLines);
  //pdRaw->SetVerts(verts);

  //tFilter->SetInput(pdRaw);
  //tFilter->Update();
  //pdRefined = tFilter->GetOutput();

  //polydata->SetPoints(pdRefined->GetPoints());
  //polydata->SetPolys(pdRefined->GetPolys());
  //polydata->SetLines(pdRefined->GetLines());
  //polydata->SetVerts(pdRefined->GetVerts());
  
  
  polydata->SetPoints(pts);
  polydata->SetLines(pLines);
  polydata->SetVerts(verts);
  polydata->SetStrips(strips);

  return 1;
}
Example #29
0
void output_saveSubcatchResults(double reportTime, FILE* file)
//
//  Input:   reportTime = elapsed simulation time (millisec)
//           file = ptr. to binary output file
//  Output:  none
//  Purpose: writes computed subcatchment results to binary file.
//
{
    int      j;
    double   f;
    double   area;
    REAL4    totalArea = 0.0f; 
    DateTime reportDate = getDateTime(reportTime);
	FILE *fptr;

	// --- dbf variables
	DBFHandle	hDBF;
	char		fieldName[128];
	int			n;
	double		f1,f0;
	double		value;
	int numFields;

    // --- update reported rainfall at each rain gage
    for ( j=0; j<Nobjects[GAGE]; j++ )
    {
        gage_setReportRainfall(j, reportDate);
    }

    // --- find where current reporting time lies between latest runoff times
    f = (reportTime - OldRunoffTime) / (NewRunoffTime - OldRunoffTime);
	f1 = 1.0 - f;
	f0 = f;

    // --- write subcatchment results to file
    for ( j=0; j<Nobjects[SUBCATCH]; j++)
    {
        // --- retrieve interpolated results for reporting time & write to file
        subcatch_getResults(j, f, SubcatchResults);
        if ( Subcatch[j].rptFlag )
            fwrite(SubcatchResults, sizeof(REAL4), NsubcatchResults, file);

        // --- update system-wide results
        area = Subcatch[j].area * UCF(LANDAREA);
        totalArea += (REAL4)area;
        SysResults[SYS_RAINFALL] +=
            (REAL4)(SubcatchResults[SUBCATCH_RAINFALL] * area);
        SysResults[SYS_SNOWDEPTH] +=
            (REAL4)(SubcatchResults[SUBCATCH_SNOWDEPTH] * area);
        SysResults[SYS_EVAP] +=
            (REAL4)(SubcatchResults[SUBCATCH_EVAP] * area);
        if ( Subcatch[j].groundwater ) SysResults[SYS_EVAP] += 
            (REAL4)(Subcatch[j].groundwater->evapLoss * UCF(EVAPRATE) * area);
        SysResults[SYS_INFIL] +=
            (REAL4)(SubcatchResults[SUBCATCH_INFIL] * area);
        SysResults[SYS_RUNOFF] += (REAL4)SubcatchResults[SUBCATCH_RUNOFF];
    }

    // --- normalize system-wide results to catchment area
    if ( UnitSystem == SI ) f = (5./9.) * (Temp.ta - 32.0);
    else f = Temp.ta;
    SysResults[SYS_TEMPERATURE] = (REAL4)f;
    SysResults[SYS_EVAP]      /= totalArea;
    SysResults[SYS_RAINFALL]  /= totalArea;
    SysResults[SYS_SNOWDEPTH] /= totalArea;
    SysResults[SYS_INFIL]     /= totalArea;

	// --- open DBF
	hDBF = DBFOpen(F2Dmesh.name, "r+b");
	if( hDBF == NULL )
	{
		//TODO
		//printf( "DBFOpen(%s,\"rb+\") failed.\n", argv[1] );
		//exit( 2 );
	}

	// --- create new field name
	n=sprintf (fieldName, "h_%07.0f", (reportTime / 1000.f));
	if( DBFAddField( hDBF, fieldName, FTDouble, 12, 6 ) == -1 )
    {
		//TODO
		//printf( "DBFAddField(%s,FTDouble,%d,%d) failed.\n", fieldName, 12, 3 );
		//exit( 4 );
    }

	n=sprintf (fieldName, "V_%07.0f", (reportTime / 1000.f));
	if( DBFAddField( hDBF, fieldName, FTDouble, 12, 6 ) == -1 )
    {
		//TODO
		//printf( "DBFAddField(%s,FTDouble,%d,%d) failed.\n", fieldName, 12, 3 );
		//exit( 4 );
    }

	// --- number of existing fields
	numFields = DBFGetFieldCount( hDBF );

    // --- write subcatchment results to file
    for ( j=0; j<Nobjects[SUBCATCH]; j++)
    {
		if (Subcatch[j].isStreet)
		{

			value = ( f1 * Subcatch[j].oldGlobalDepth + f0 * Subcatch[j].newGlobalDepth ) * UCF(LENGTH);

			//Write value
			DBFWriteDoubleAttribute(hDBF, Subcatch[j].dbf_record, numFields - 2, value );

			value = ( f1 * Subcatch[j].oldVel + f0 * Subcatch[j].newVel ) * UCF(LENGTH);

			//Write value
			DBFWriteDoubleAttribute(hDBF, Subcatch[j].dbf_record, numFields - 1, value );

		}
	}

	//CLose
	DBFClose( hDBF );

	// --- create file to print outflow
	fptr = fopen(F2Doutflow.name, "a+");

	if (fptr == NULL)
	{
		printf("ERROR: Impossible to create Outflow.txt\n");
	} else {
		fprintf(fptr, "%12.3f  %12.3f\n", (reportTime / 1000.f), M2DControl.totalOutflow);

		fclose(fptr);
	}


}
Example #30
0
int load_table(int t)
{
    int i, j, ncols, nrows, dbfcol;
    DBFHandle dbf;
    char *buf;
    ROW *rows;
    VALUE *val;

    G_debug(2, "load_table(): tab = %d", t);

    if (db.tables[t].loaded == TRUE)	/*already loaded */
        return DB_OK;

    dbf = DBFOpen(db.tables[t].file, "r");
    if (dbf == NULL) {
        append_error("Cannot open dbf file.\n");
        return DB_FAILED;
    }

    ncols = db.tables[t].ncols;
    nrows = DBFGetRecordCount(dbf);
    rows = db.tables[t].rows;
    rows = (ROW *) G_malloc(nrows * sizeof(ROW));
    db.tables[t].arows = nrows;

    G_debug(2, "  ncols = %d nrows = %d", ncols, nrows);

    for (i = 0; i < nrows; i++) {
        rows[i].alive = TRUE;
        rows[i].values = (VALUE *) G_calloc(ncols, sizeof(VALUE));

        for (j = 0; j < ncols; j++) {
            val = &(rows[i].values[j]);

            dbfcol = j;

            val->is_null = DBFIsAttributeNULL(dbf, i, dbfcol);
            if (!(val->is_null)) {
                switch (db.tables[t].cols[j].type) {
                case DBF_INT:
                    val->i = DBFReadIntegerAttribute(dbf, i, dbfcol);
                    break;
                case DBF_CHAR:
                    buf = (char *)DBFReadStringAttribute(dbf, i, dbfcol);
                    save_string(val, buf);
                    break;
                case DBF_DOUBLE:
                    val->d = DBFReadDoubleAttribute(dbf, i, dbfcol);
                    break;
                }
            }
        }
    }

    DBFClose(dbf);

    db.tables[t].rows = rows;
    db.tables[t].nrows = nrows;
    db.tables[t].loaded = TRUE;

    return DB_OK;
}