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; }
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 ); }
CommandDef (index, clientData, interp, objc, objv) { Handle *handle; int index, fieldCount, i; DBFHandle dbfHandle; Tcl_Obj *resultPtr; if (objc != 3) { Tcl_WrongNumArgs (interp, 1, objv, "filename index"); return TCL_ERROR; } if (DbfGetHandleFromObj (interp, objv[1], &handle) != TCL_OK) { return TCL_ERROR; } if (Tcl_GetIntFromObj (interp, objv[2], &index) != TCL_OK) { return TCL_ERROR; } dbfHandle = handle->dbfHandle; fieldCount = DBFGetFieldCount (dbfHandle); resultPtr = Tcl_GetObjResult (interp); for (i = 0; i < fieldCount; i++) { if (Tcl_ListObjAppendElement (interp, resultPtr, NewAttributeObj (dbfHandle, index, i)) != TCL_OK) { return TCL_ERROR; } } return TCL_OK; }
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); }
/////////////////////////////////////////////////////////////////////////////// // Stellt fest, ob ein bestimmtes Feld bereits in der Datei enthalten ist HRESULT CArcViewLayer::FieldExists (LPCSTR pcName, DBFFieldType rgType, int *piField) { CFieldNames::iterator it = m_Names.find (pcName); if (it != m_Names.end()) { int iCnt = DBFGetFieldCount(m_hDBF); int iWidth = 0; int iDecimals = 0; char cbBuffer[_MAX_PATH]; for (int i = 0; i < iCnt; ++i) { DBFFieldType rgActType = DBFGetFieldInfo(m_hDBF, i, cbBuffer, &iWidth, &iDecimals); if ((*it).second == os_string(cbBuffer)) { if (NULL != piField) *piField = i; if (rgType == rgActType || rgActType == FTString) return S_OK; // found Field else return S_FALSE; // found, but type does not match } } } return E_FAIL; // does not exist }
inline Tags parseTags(DBFHandle dbfFile, int k) const { char title[12]; int fieldCount = DBFGetFieldCount(dbfFile); Tags tags; tags.reserve(fieldCount); for (int i = 0; i < fieldCount; i++) { if (DBFIsAttributeNULL(dbfFile, k, i)) continue; utymap::formats::Tag tag; int width, decimals; DBFFieldType eType = DBFGetFieldInfo(dbfFile, i, title, &width, &decimals); tag.key = std::string(title); { switch (eType) { case FTString: tag.value = DBFReadStringAttribute(dbfFile, k, i); break; case FTInteger: tag.value = to_string(DBFReadIntegerAttribute(dbfFile, k, i)); break; case FTDouble: tag.value = to_string(DBFReadDoubleAttribute(dbfFile, k, i)); break; default: break; } } tags.push_back(tag); } return std::move(tags); }
CommandDef (values, clientData, interp, objc, objv) { Handle *handle; DBFHandle dbfHandle; int fieldCount, i; Tcl_Obj *resultPtr, *listPtr; if (objc != 2) { Tcl_WrongNumArgs (interp, 1, objv, "filename"); return TCL_ERROR; } if (DbfGetHandleFromObj (interp, objv[1], &handle) != TCL_OK) { return TCL_ERROR; } dbfHandle = handle->dbfHandle; fieldCount = DBFGetFieldCount (dbfHandle); resultPtr = Tcl_GetObjResult (interp); for (i = 0; i < fieldCount; i++) { listPtr = Tcl_NewObj (); if (ListObjAppendField (interp, listPtr, dbfHandle, i) != TCL_OK) { return TCL_ERROR; } if (Tcl_ListObjAppendElement (interp, resultPtr, listPtr) != TCL_OK) { return TCL_ERROR; } } return TCL_OK; }
// 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; } }
/////////////////////////////////////////////////////////////////////////////// // anlegen eines neuen Feldes in der DBase-Datei HRESULT CArcViewLayer::AddField(LPCSTR pcName, DBFFieldType rgTyp, int iLen, int iDecimal, int *piField) { if (NULL == piField) return E_POINTER; *piField = -1; CFieldNames::iterator it = m_Names.find (pcName); if (it == m_Names.end()) { // Namen zuordnen pair<CFieldNames::iterator, bool> p = m_Names.insert(CFieldNames::value_type(pcName, GetUniqueFieldName(pcName))); if (p.second) it = p.first; } if (it != m_Names.end()) { // DBasefeld anlegen if (FTString == rgTyp && iLen > MAX_DBASEFIELD_LEN) iLen = MAX_DBASEFIELD_LEN; *piField = DBFAddField(m_hDBF, (*it).second.c_str(), rgTyp, iLen, iDecimal); // ggf. existiert das Feld schon in der DBaseDatei (eine bereits exportierte // Datenquelle hat es hinterlassen) if (-1 != *piField) return S_OK; // found Field int iCnt = DBFGetFieldCount(m_hDBF); int iWidth = 0; int iDecimals = 0; char cbBuffer[_MAX_PATH]; for (int i = 0; i < iCnt; ++i) { DBFFieldType rgActType = DBFGetFieldInfo(m_hDBF, i, cbBuffer, &iWidth, &iDecimals); if ((*it).second == os_string(cbBuffer) && (rgTyp == rgActType || rgActType == FTString)) { *piField = i; return S_OK; // found Field } } return E_FAIL; } return E_FAIL; // could not create field }
bool ShapelibProxy::getFeatureClassProperties(const std::string &handle, ArcProxyLib::FeatureClassProperties &properties, std::string &errorMessage) { std::map<std::string, ShapelibHandle>::iterator iter = mHandles.find(handle); if (iter == mHandles.end()) { errorMessage = "Could not find handle"; return false; } ShapelibHandle& shapelibHandle = iter->second; int count = 0; ArcProxyLib::FeatureType featureType = ArcProxyLib::UNKNOWN; if (!getTypeAndCount(shapelibHandle, errorMessage, featureType, count)) { return false; } properties.setFeatureCount(count); properties.setFeatureType(featureType); std::vector<std::string> fields; std::vector<std::string> types; std::vector<std::string> sampleValues; // fields int fieldCount = DBFGetFieldCount(shapelibHandle.getDbfHandle()); for (int i = 0; i < fieldCount; ++i) { std::string name; std::string type; std::string value; if (getFieldAttributes(shapelibHandle, name, type, value, i, 0)) { fields.push_back(name); types.push_back(type); sampleValues.push_back(value); } } properties.setFields(fields); properties.setTypes(types); properties.setSampleValues(sampleValues); return true; }
CommandDef (size, clientData, interp, objc, objv) { Handle *handle; if (objc != 2) { Tcl_WrongNumArgs (interp, 1, objv, "filename"); return TCL_ERROR; } if (DbfGetHandleFromObj (interp, objv[1], &handle) != TCL_OK) { return TCL_ERROR; } Tcl_SetIntObj (Tcl_GetObjResult (interp), DBFGetFieldCount (handle->dbfHandle)); return TCL_OK; }
bool compareDBF(DBFHandle iDBF, int iRecord, DBFHandle jDBF, int jRecord, bool print) { int i,j; int temp; bool result; DBFFieldType eType; char szTitle[12]; // Column heading int nWidth, nDecimals; result = false; for( i = 0; i < DBFGetFieldCount(iDBF); i++ ) { j = columnMatchArray[i]; if( j < 0 ) continue; eType = DBFGetFieldInfo( iDBF, i, szTitle, &nWidth, &nDecimals ); assert( nWidth < BUFFER_MAX ); memcpy( &iBuffer, DBFReadStringAttribute( iDBF, iRecord, i ), nWidth ); memcpy( &jBuffer, DBFReadStringAttribute( jDBF, jRecord, j ), nWidth ); /* Convert numbers, compare everything else as a string */ if( eType == FTDouble ) temp = (atof( iBuffer ) != atof( jBuffer ) ); else if( eType == FTInteger ) temp = (atoi( iBuffer ) != atoi( jBuffer ) ); else temp = memcmp ( &iBuffer, &jBuffer, nWidth ); /* Unless they are both NULL, flag record as different */ if( temp ) { result = true; if( DBFIsAttributeNULL( iDBF, iRecord, i ) && DBFIsAttributeNULL( jDBF, jRecord, j ) ) result = false; } if( temp && print ) { //printf("%d wide record %d and %d differ (etype=%d)\n", nWidth, iRecord, jRecord, eType ); iBuffer[ nWidth ] = 0; jBuffer[ nWidth ] = 0; printf("%s: %s >>> %s\n", szTitle, &iBuffer, &jBuffer); } } return( result ); }
int DBFGetFieldIndex(DBFHandle psDBF, const char *pszFieldName) { char name[12], name1[12], name2[12]; int i; strncpy(name1, pszFieldName,11); name1[11] = '\0'; str_to_upper(name1); for( i = 0; i < DBFGetFieldCount(psDBF); i++ ) { DBFGetFieldInfo( psDBF, i, name, NULL, NULL ); strncpy(name2,name,11); str_to_upper(name2); if(!strncmp(name1,name2,10)) return(i); } return(-1); }
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); }
NRCommandDef (foreach, clientData, interp, objc, objv) { Handle *handle; DBFHandle dbfHandle; int recordCount, fieldCount; ForeachState *statePtr; if (objc != 4) { Tcl_WrongNumArgs (interp, 1, objv, "var filename command"); return TCL_ERROR; } if (DbfGetHandleFromObj (interp, objv[2], &handle) != TCL_OK) { return TCL_ERROR; } if ((recordCount = DBFGetRecordCount (dbfHandle = handle->dbfHandle)) == 0) { return TCL_OK; } if ((fieldCount = DBFGetFieldCount (dbfHandle)) == 0) { return TCL_OK; } statePtr = (ForeachState *) ckalloc (sizeof (*statePtr)); statePtr->i = 0; statePtr->length = recordCount; statePtr->size = fieldCount; if (ForeachAssignments (interp, statePtr, objv[1], dbfHandle) != TCL_OK) { return TCL_ERROR; } Tcl_NRAddCallback (interp, ForeachLoopStep, statePtr, objv[1], dbfHandle, objv[3]); return Tcl_NREvalObj (interp, objv[3], 0); }
/* -------------------------------------------------------------------- */ void printDBF(DBFHandle iDBF, int iRecord) { int i; char szTitle[12]; // Column heading int nWidth, nDecimals; char szFormat[32]; for( i = 0; i < DBFGetFieldCount(iDBF); i++ ) { DBFFieldType eType; eType = DBFGetFieldInfo( iDBF, i, szTitle, &nWidth, &nDecimals ); if( bMultiLine ) { printf( "\n%s: ", szTitle ); } else { printf("|"); } sprintf( szFormat, "%%-%ds", nWidth ); printf( szFormat, DBFReadStringAttribute( iDBF, iRecord, i ) ); } printf("\n"); }
/* -------------------------------------------------------------------- */ void printHeader(DBFHandle xDBF, SHPHandle xSHP) { double adfMinBound[4], adfMaxBound[4]; int xEntities; int xShapeType; int nWidth, nDecimals; int i; char szTitle[12]; SHPGetInfo( xSHP, &xEntities, &xShapeType, adfMinBound, adfMaxBound ); printf( "Shapefile Type: %s, %d shapes ", SHPTypeName( xShapeType ), xEntities ); printf( "%d database records\n", DBFGetRecordCount(xDBF) ); if( bVerbose ) { for( i = 0; i < DBFGetFieldCount(xDBF); i++ ) { DBFFieldType eType; const char *pszTypeName; eType = DBFGetFieldInfo( xDBF, 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 ); } } }
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 ); }
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 ); }
//---------------------------------------------------------------------------- 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; }
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); } }
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; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { /* Pointer to temporary matlab array */ const mxArray *mx; mxArray *m_shape_type; int nShapeType, nEntities, i, j, k, iPart, nFields, nStructElem, isPoint, firstInPoints = 1; int num_dbf_fields, num_dbf_records; /* number of DBF attributes, records */ int buflen; /* length of input shapefile name */ int status; /* success or failure */ char *shapefile; /* holder for input shapefile name */ const char *pszPartType = ""; /* Not used. */ double adfMinBound[4], adfMaxBound[4]; /* pointer to the shapefile */ SHPHandle hSHP; SHPObject *psShape; DBFHandle dbh; /* handle for DBF file */ /* This structure will hold a description of each field in the DBF file. */ typedef struct DBF_Field_Descriptor { char pszFieldName[12]; DBFFieldType field_type; } DBF_Field_Descriptor; DBF_Field_Descriptor *dbf_field; /* stores individual values from the DBF. */ int dbf_integer_val, dims[2], *p_parts_ptr, nNaNs, c, i_start, i_stop; char *dbf_char_val, error_buffer[500]; char *fnames[100]; /* holds name of fields */ mxArray *out_struct, *x_out, *y_out, *z_out, *bbox, *p_parts; double *x_out_ptr, *y_out_ptr, *z_out_ptr, *bb_ptr, nan, dbf_double_val; size_t sizebuf; /* Initialize the dbf record. */ dbf_field = NULL; /* Check for proper number of arguments */ if (nrhs != 1) mexErrMsgTxt("One input arguments are required."); if (nlhs != 2) mexErrMsgTxt("Two output arguments required."); /* Make sure the input is a proper string. */ if ( mxIsChar(prhs[0]) != 1 ) mexErrMsgTxt("Shapefile parameter must be a string\n" ); if ( mxGetM(prhs[0]) != 1 ) mexErrMsgTxt("Shapefile parameter must be a row vector, not a column string\n" ); buflen = mxGetN(prhs[0]) + 1; shapefile = mxCalloc( buflen, sizeof(char) ); /* copy the string data from prhs[0] into a C string. */ status = mxGetString( prhs[0], shapefile, buflen ); if ( status != 0 ) mxErrMsgTxt( "Not enough space for shapefile argument.\n" ); /* -------------------------------------------------------------------- */ /* Open the passed shapefile. */ /* -------------------------------------------------------------------- */ hSHP = SHPOpen( shapefile, "rb" ); if( hSHP == NULL ) mxErrMsgTxt( "Unable to open:%s\n", shapefile ); /* -------------------------------------------------------------------- */ /* Get the needed information about the shapefile. */ /* -------------------------------------------------------------------- */ SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound ); /* Make sure that we can handle the type. */ switch ( nShapeType ) { case SHPT_POINT: break; case SHPT_POINTZ: break; case SHPT_ARC: break; case SHPT_ARCZ: break; case SHPT_POLYGON: break; case SHPT_POLYGONZ: break; case SHPT_MULTIPOINT: /* JL */ break; default: sprintf ( error_buffer, "Unhandled shape code %d (%s)", nShapeType, SHPTypeName ( nShapeType ) ); mexErrMsgTxt( error_buffer ); } /* Create the output shape type parameter. */ plhs[1] = mxCreateString ( SHPTypeName ( nShapeType ) ); /* Open the DBF, and retrieve the number of fields and records */ dbh = DBFOpen (shapefile, "rb"); num_dbf_fields = DBFGetFieldCount ( dbh ); num_dbf_records = DBFGetRecordCount ( dbh ); /* Allocate space for a description of each record, and populate it. * I allocate space for two extra "dummy" records that go in positions * 0 and 1. These I reserve for the xy data. */ nFields = 3; if ( (nShapeType == SHPT_POLYGONZ) || (nShapeType == SHPT_ARCZ) || (nShapeType == SHPT_POINTZ) ) nFields++; dbf_field = (DBF_Field_Descriptor *) mxMalloc ( (num_dbf_fields+nFields) * sizeof ( DBF_Field_Descriptor ) ); if ( dbf_field == NULL ) mexErrMsgTxt("Memory allocation for DBF_Field_Descriptor failed."); for ( j = 0; j < num_dbf_fields; ++j ) dbf_field[j+nFields].field_type = DBFGetFieldInfo ( dbh, j, dbf_field[j+nFields].pszFieldName, NULL, NULL ); fnames[0] = strdup ( "X" ); fnames[1] = strdup ( "Y" ); if ( (nShapeType == SHPT_POLYGONZ) || (nShapeType == SHPT_ARCZ) || (nShapeType == SHPT_POINTZ) ) { fnames[2] = strdup ( "Z" ); fnames[3] = strdup ( "BoundingBox" ); } else fnames[2] = strdup ( "BoundingBox" ); for ( j = 0; j < num_dbf_fields; ++j ) fnames[j+nFields] = strdup ( dbf_field[j+nFields].pszFieldName ); /* To hold information on eventual polygons with rings */ /*fnames[num_dbf_fields+3] = strdup ( "nParts" );*/ /*fnames[num_dbf_fields+4] = strdup ( "PartsIndex" );*/ /* Allocate space for the output structure. */ isPoint = ( nShapeType == SHPT_POINT || nShapeType == SHPT_POINTZ ) ? 1: 0; nStructElem = ( nShapeType == SHPT_POINT || nShapeType == SHPT_POINTZ ) ? 1: nEntities; out_struct = mxCreateStructMatrix ( nStructElem, 1, nFields + num_dbf_fields, (const char **)fnames ); /* create the BoundingBox */ dims[0] = 4; dims[1] = 2; bbox = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL ); bb_ptr = mxGetData ( bbox ); for (i = 0; i < 4; i++) bb_ptr[i] = adfMinBound[i]; for (i = 0; i < 4; i++) bb_ptr[i+4] = adfMaxBound[i]; mxSetField ( out_struct, 0, "BoundingBox", bbox ); nan = mxGetNaN(); /* -------------------------------------------------------------------- */ /* Skim over the list of shapes, printing all the vertices. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nEntities; i++ ) { psShape = SHPReadObject( hSHP, i ); /* Create the fields in this struct element. */ if ( !isPoint ) { nNaNs = psShape->nParts > 1 ? psShape->nParts : 0; dims[0] = psShape->nVertices + nNaNs; dims[1] = 1; x_out = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL ); x_out_ptr = mxGetData ( x_out ); y_out = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL ); y_out_ptr = mxGetData ( y_out ); if ( (nShapeType == SHPT_POLYGONZ) || (nShapeType == SHPT_POINTZ) || (nShapeType == SHPT_ARCZ)) { z_out = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL ); z_out_ptr = mxGetData ( z_out ); } } else if (firstInPoints) { /* Allocate all memory we'll need */ x_out = mxCreateDoubleMatrix (nEntities, 1, mxREAL); x_out_ptr = mxGetPr ( x_out ); y_out = mxCreateDoubleMatrix (nEntities, 1, mxREAL); y_out_ptr = mxGetPr ( y_out ); if (nShapeType == SHPT_POINTZ) { z_out = mxCreateDoubleMatrix (nEntities, 1, mxREAL); z_out_ptr = mxGetPr ( z_out ); } firstInPoints = 0; } if (!isPoint && psShape->nParts > 1) { for (k = c = 0; k < psShape->nParts; k++) { i_start = psShape->panPartStart[k]; if (k < psShape->nParts - 1) i_stop = psShape->panPartStart[k+1]; else i_stop = psShape->nVertices; if ( nShapeType == SHPT_POLYGONZ ) { for (j = i_start; j < i_stop; c++, j++) { x_out_ptr[c] = psShape->padfX[j]; y_out_ptr[c] = psShape->padfY[j]; z_out_ptr[c] = psShape->padfZ[j]; } x_out_ptr[c] = nan; y_out_ptr[c] = nan; z_out_ptr[c] = nan; } else { for (j = i_start; j < i_stop; c++, j++) { x_out_ptr[c] = psShape->padfX[j]; y_out_ptr[c] = psShape->padfY[j]; } x_out_ptr[c] = nan; y_out_ptr[c] = nan; } c++; } } else if ( isPoint ) { x_out_ptr[i] = *psShape->padfX; y_out_ptr[i] = *psShape->padfY; if (nShapeType == SHPT_POINTZ) z_out_ptr[i] = *psShape->padfZ; if (i > 0) { SHPDestroyObject( psShape ); continue; } } else { /* Just copy the vertices over. */ sizebuf = mxGetElementSize ( x_out ) * psShape->nVertices; memcpy ( (void *) x_out_ptr, (void *) psShape->padfX, sizebuf ); memcpy ( (void *) y_out_ptr, (void *) psShape->padfY, sizebuf ); if ( (nShapeType == SHPT_POLYGONZ) || (nShapeType == SHPT_ARCZ)) memcpy ( (void *) z_out_ptr, (void *) psShape->padfZ, sizebuf ); } mxSetField ( out_struct, i, "X", x_out ); mxSetField ( out_struct, i, "Y", y_out ); if ( (nShapeType == SHPT_POLYGONZ) || (nShapeType == SHPT_ARCZ) ) mxSetField ( out_struct, i, "Z", z_out ); bbox = mxCreateNumericMatrix ( 4, 2, mxDOUBLE_CLASS, mxREAL ); bb_ptr = (double *)mxGetData ( bbox ); bb_ptr[0] = psShape->dfXMin; bb_ptr[1] = psShape->dfYMin; bb_ptr[2] = psShape->dfZMin; bb_ptr[3] = psShape->dfMMin; bb_ptr[4] = psShape->dfXMax; bb_ptr[5] = psShape->dfYMax; bb_ptr[6] = psShape->dfZMax; bb_ptr[7] = psShape->dfMMax; if (i > 0) /* First BB contains the ensemble extent */ mxSetField ( out_struct, i, "BoundingBox", bbox ); for ( j = 0; j < num_dbf_fields; ++j ) { switch ( dbf_field[j+nFields].field_type ) { case FTString: dbf_char_val = (char *) DBFReadStringAttribute ( dbh, i, j ); mxSetField ( out_struct, i, dbf_field[j+nFields].pszFieldName, mxCreateString ( dbf_char_val ) ); break; case FTDouble: dbf_double_val = DBFReadDoubleAttribute ( dbh, i, j ); mxSetField ( out_struct, i, dbf_field[j+nFields].pszFieldName, mxCreateDoubleScalar ( dbf_double_val ) ); break; case FTInteger: case FTLogical: dbf_integer_val = DBFReadIntegerAttribute ( dbh, i, j ); dbf_double_val = dbf_integer_val; mxSetField ( out_struct, i, dbf_field[j+nFields].pszFieldName, mxCreateDoubleScalar ( dbf_double_val ) ); break; default: sprintf ( error_buffer, "Unhandled code %d, shape %d, record %d\n", dbf_field[j+nFields].field_type, i, j ); mexErrMsgTxt("Unhandled code"); } } SHPDestroyObject( psShape ); } if ( isPoint ) { /* In this case we still need to "send the true data out" */ mxSetField ( out_struct, 0, "X", x_out ); mxSetField ( out_struct, 0, "Y", y_out ); if (nShapeType == SHPT_POINTZ) mxSetField ( out_struct, 0, "Z", z_out ); } /* Clean up, close up shop. */ SHPClose( hSHP ); DBFClose ( dbh ); if ( dbf_field != NULL ) mxFree ( (void *)dbf_field ); plhs[0] = out_struct; }
void dibSHP::updateFile() { QString fileName = fileedit->text(); int num_ent, st, num_field; double min_bound[4], max_bound[4]; QStringList txtformats; char field_name[12]; QFileInfo fi = QFileInfo(fileName); if (fi.suffix() != "shp") return; QString file = fi.canonicalFilePath (); if (file.isEmpty()) return; SHPHandle sh = SHPOpen( file.toLocal8Bit(), "rb" ); SHPGetInfo( sh, &num_ent, &st, min_bound, max_bound ); SHPClose( sh ); DBFHandle dh = DBFOpen( file.toLocal8Bit(), "rb" ); num_field = DBFGetFieldCount( dh ); for( int i = 0; i < num_field; i++ ) { DBFGetFieldInfo( dh, i, field_name,NULL, NULL); txtformats << field_name; } DBFClose( dh ); txtformats.sort(); layerdata->clear(); layerdata->addItems(txtformats); colordata->clear(); colordata->addItems(txtformats); ltypedata->clear(); ltypedata->addItems(txtformats); lwidthdata->clear(); lwidthdata->addItems(txtformats); pointdata->clear(); pointdata->addItems(txtformats); switch (st) { case SHPT_POINT: formattype->setText(tr("Point")); pointbox->setDisabled(false); break; case SHPT_POINTM: formattype->setText(tr("Point+Measure")); pointbox->setDisabled(false); break; case SHPT_POINTZ: //3d point formattype->setText(tr("3D Point")); pointbox->setDisabled(false); break; case SHPT_MULTIPOINT: formattype->setText(tr("Multi Point")); pointbox->setDisabled(false); break; case SHPT_MULTIPOINTM: formattype->setText(tr("Multi Point+Measure")); pointbox->setDisabled(false); break; case SHPT_MULTIPOINTZ: formattype->setText(tr("3D Multi Point")); pointbox->setDisabled(false); break; case SHPT_ARC: formattype->setText(tr("Arc")); pointbox->setDisabled(true); break; case SHPT_ARCM: formattype->setText(tr("Arc+Measure")); pointbox->setDisabled(true); break; case SHPT_ARCZ: formattype->setText(tr("3D Arc")); pointbox->setDisabled(true); break; case SHPT_POLYGON: formattype->setText(tr("Poligon")); pointbox->setDisabled(true); break; case SHPT_POLYGONM: formattype->setText(tr("Poligon+Measure")); pointbox->setDisabled(true); break; case SHPT_POLYGONZ: formattype->setText(tr("3D Poligon")); pointbox->setDisabled(true); break; case SHPT_MULTIPATCH: formattype->setText(tr("Multipatch")); pointbox->setDisabled(true); break; case SHPT_NULL: default: formattype->setText(tr("Unknoun")); pointbox->setDisabled(true); break; } }
/* Open the shapefile and extract the relevant field information */ int ShpLoaderOpenShape(SHPLOADERSTATE *state) { SHPObject *obj = NULL; int j, z; int ret = SHPLOADEROK; int field_precision, field_width; char name[MAXFIELDNAMELEN]; char name2[MAXFIELDNAMELEN]; DBFFieldType type = -1; char *utf8str; /* If we are reading the entire shapefile, open it */ if (state->config->readshape == 1) { state->hSHPHandle = SHPOpen(state->config->shp_file, "rb"); if (state->hSHPHandle == NULL) { snprintf(state->message, SHPLOADERMSGLEN, _("%s: shape (.shp) or index files (.shx) can not be opened, will just import attribute data."), state->config->shp_file); state->config->readshape = 0; ret = SHPLOADERWARN; } } /* Open the DBF (attributes) file */ state->hDBFHandle = DBFOpen(state->config->shp_file, "rb"); if ((state->hSHPHandle == NULL && state->config->readshape == 1) || state->hDBFHandle == NULL) { snprintf(state->message, SHPLOADERMSGLEN, _("%s: dbf file (.dbf) can not be opened."), state->config->shp_file); return SHPLOADERERR; } /* If reading the whole shapefile (not just attributes)... */ if (state->config->readshape == 1) { SHPGetInfo(state->hSHPHandle, &state->num_entities, &state->shpfiletype, NULL, NULL); /* If null_policy is set to abort, check for NULLs */ if (state->config->null_policy == POLICY_NULL_ABORT) { /* If we abort on null items, scan the entire file for NULLs */ for (j = 0; j < state->num_entities; j++) { obj = SHPReadObject(state->hSHPHandle, j); if (!obj) { snprintf(state->message, SHPLOADERMSGLEN, _("Error reading shape object %d"), j); return SHPLOADERERR; } if (obj->nVertices == 0) { snprintf(state->message, SHPLOADERMSGLEN, _("Empty geometries found, aborted.)")); return SHPLOADERERR; } SHPDestroyObject(obj); } } /* Check the shapefile type */ int geomtype = 0; switch (state->shpfiletype) { case SHPT_POINT: /* Point */ state->pgtype = "POINT"; geomtype = POINTTYPE; state->pgdims = 2; break; case SHPT_ARC: /* PolyLine */ state->pgtype = "MULTILINESTRING"; geomtype = MULTILINETYPE ; state->pgdims = 2; break; case SHPT_POLYGON: /* Polygon */ state->pgtype = "MULTIPOLYGON"; geomtype = MULTIPOLYGONTYPE; state->pgdims = 2; break; case SHPT_MULTIPOINT: /* MultiPoint */ state->pgtype = "MULTIPOINT"; geomtype = MULTIPOINTTYPE; state->pgdims = 2; break; case SHPT_POINTM: /* PointM */ geomtype = POINTTYPE; state->has_m = 1; state->pgtype = "POINTM"; state->pgdims = 3; break; case SHPT_ARCM: /* PolyLineM */ geomtype = MULTILINETYPE; state->has_m = 1; state->pgtype = "MULTILINESTRINGM"; state->pgdims = 3; break; case SHPT_POLYGONM: /* PolygonM */ geomtype = MULTIPOLYGONTYPE; state->has_m = 1; state->pgtype = "MULTIPOLYGONM"; state->pgdims = 3; break; case SHPT_MULTIPOINTM: /* MultiPointM */ geomtype = MULTIPOINTTYPE; state->has_m = 1; state->pgtype = "MULTIPOINTM"; state->pgdims = 3; break; case SHPT_POINTZ: /* PointZ */ geomtype = POINTTYPE; state->has_m = 1; state->has_z = 1; state->pgtype = "POINT"; state->pgdims = 4; break; case SHPT_ARCZ: /* PolyLineZ */ state->pgtype = "MULTILINESTRING"; geomtype = MULTILINETYPE; state->has_z = 1; state->has_m = 1; state->pgdims = 4; break; case SHPT_POLYGONZ: /* MultiPolygonZ */ state->pgtype = "MULTIPOLYGON"; geomtype = MULTIPOLYGONTYPE; state->has_z = 1; state->has_m = 1; state->pgdims = 4; break; case SHPT_MULTIPOINTZ: /* MultiPointZ */ state->pgtype = "MULTIPOINT"; geomtype = MULTIPOINTTYPE; state->has_z = 1; state->has_m = 1; state->pgdims = 4; break; default: state->pgtype = "GEOMETRY"; geomtype = COLLECTIONTYPE; state->has_z = 1; state->has_m = 1; state->pgdims = 4; snprintf(state->message, SHPLOADERMSGLEN, _("Unknown geometry type: %d\n"), state->shpfiletype); return SHPLOADERERR; break; } /* Force Z/M-handling if configured to do so */ switch(state->config->force_output) { case FORCE_OUTPUT_2D: state->has_z = 0; state->has_m = 0; state->pgdims = 2; break; case FORCE_OUTPUT_3DZ: state->has_z = 1; state->has_m = 0; state->pgdims = 3; break; case FORCE_OUTPUT_3DM: state->has_z = 0; state->has_m = 1; state->pgdims = 3; break; case FORCE_OUTPUT_4D: state->has_z = 1; state->has_m = 1; state->pgdims = 4; break; default: /* Simply use the auto-detected values above */ break; } /* If in simple geometry mode, alter names for CREATE TABLE by skipping MULTI */ if (state->config->simple_geometries) { if ((geomtype == MULTIPOLYGONTYPE) || (geomtype == MULTILINETYPE) || (geomtype == MULTIPOINTTYPE)) { /* Chop off the "MULTI" from the string. */ state->pgtype += 5; } } } else { /* Otherwise just count the number of records in the DBF */ state->num_entities = DBFGetRecordCount(state->hDBFHandle); } /* Get the field information from the DBF */ state->num_fields = DBFGetFieldCount(state->hDBFHandle); state->num_records = DBFGetRecordCount(state->hDBFHandle); /* Allocate storage for field information */ state->field_names = malloc(state->num_fields * sizeof(char*)); state->types = (DBFFieldType *)malloc(state->num_fields * sizeof(int)); state->widths = malloc(state->num_fields * sizeof(int)); state->precisions = malloc(state->num_fields * sizeof(int)); state->pgfieldtypes = malloc(state->num_fields * sizeof(char *)); state->col_names = malloc((state->num_fields + 2) * sizeof(char) * MAXFIELDNAMELEN); /* Generate a string of comma separated column names of the form "(col1, col2 ... colN)" for the SQL insertion string */ strcpy(state->col_names, "(" ); for (j = 0; j < state->num_fields; j++) { type = DBFGetFieldInfo(state->hDBFHandle, j, name, &field_width, &field_precision); state->types[j] = type; state->widths[j] = field_width; state->precisions[j] = field_precision; if (state->config->encoding) { char *encoding_msg = _("Try \"LATIN1\" (Western European), or one of the values described at http://www.gnu.org/software/libiconv/."); int rv = utf8(state->config->encoding, name, &utf8str); if (rv != UTF8_GOOD_RESULT) { if ( rv == UTF8_BAD_RESULT ) snprintf(state->message, SHPLOADERMSGLEN, _("Unable to convert field name \"%s\" to UTF-8 (iconv reports \"%s\"). Current encoding is \"%s\". %s"), utf8str, strerror(errno), state->config->encoding, encoding_msg); else if ( rv == UTF8_NO_RESULT ) snprintf(state->message, SHPLOADERMSGLEN, _("Unable to convert field name to UTF-8 (iconv reports \"%s\"). Current encoding is \"%s\". %s"), strerror(errno), state->config->encoding, encoding_msg); else snprintf(state->message, SHPLOADERMSGLEN, _("Unexpected return value from utf8()")); if ( rv == UTF8_BAD_RESULT ) free(utf8str); return SHPLOADERERR; } strncpy(name, utf8str, MAXFIELDNAMELEN); free(utf8str); } /* * Make field names lowercase unless asked to * keep identifiers case. */ if (!state->config->quoteidentifiers) strtolower(name); /* * Escape names starting with the * escape char (_), those named 'gid' * or after pgsql reserved attribute names */ if (name[0] == '_' || ! strcmp(name, "gid") || ! strcmp(name, "tableoid") || ! strcmp(name, "cmin") || ! strcmp(name, "cmax") || ! strcmp(name, "xmin") || ! strcmp(name, "xmax") || ! strcmp(name, "primary") || ! strcmp(name, "oid") || ! strcmp(name, "ctid")) { strncpy(name2 + 2, name, MAXFIELDNAMELEN - 2); name2[0] = '_'; name2[1] = '_'; strcpy(name, name2); } /* Avoid duplicating field names */ for (z = 0; z < j ; z++) { if (strcmp(state->field_names[z], name) == 0) { strncat(name, "__", MAXFIELDNAMELEN); snprintf(name + strlen(name), MAXFIELDNAMELEN, "%i", j); break; } } state->field_names[j] = malloc(strlen(name) + 1); strcpy(state->field_names[j], name); /* Now generate the PostgreSQL type name string and width based upon the shapefile type */ switch (state->types[j]) { case FTString: state->pgfieldtypes[j] = malloc(strlen("varchar") + 1); strcpy(state->pgfieldtypes[j], "varchar"); break; case FTDate: state->pgfieldtypes[j] = malloc(strlen("date") + 1); strcpy(state->pgfieldtypes[j], "date"); break; case FTInteger: /* Determine exact type based upon field width */ if (state->config->forceint4 || (state->widths[j] >=5 && state->widths[j] < 10)) { state->pgfieldtypes[j] = malloc(strlen("int4") + 1); strcpy(state->pgfieldtypes[j], "int4"); } else if (state->widths[j] < 5) { state->pgfieldtypes[j] = malloc(strlen("int2") + 1); strcpy(state->pgfieldtypes[j], "int2"); } else { state->pgfieldtypes[j] = malloc(strlen("numeric") + 1); strcpy(state->pgfieldtypes[j], "numeric"); } break; case FTDouble: /* Determine exact type based upon field width */ if (state->widths[j] > 18) { state->pgfieldtypes[j] = malloc(strlen("numeric") + 1); strcpy(state->pgfieldtypes[j], "numeric"); } else { state->pgfieldtypes[j] = malloc(strlen("float8") + 1); strcpy(state->pgfieldtypes[j], "float8"); } break; case FTLogical: state->pgfieldtypes[j] = malloc(strlen("boolean") + 1); strcpy(state->pgfieldtypes[j], "boolean"); break; default: snprintf(state->message, SHPLOADERMSGLEN, _("Invalid type %x in DBF file"), state->types[j]); return SHPLOADERERR; } strcat(state->col_names, "\""); strcat(state->col_names, name); if (state->config->readshape == 1 || j < (state->num_fields - 1)) { /* Don't include last comma if its the last field and no geometry field will follow */ strcat(state->col_names, "\","); } else { strcat(state->col_names, "\""); } } /* Append the geometry column if required */ if (state->config->readshape == 1) strcat(state->col_names, state->geo_col); strcat(state->col_names, ")"); /* Return status */ return ret; }
SEXP Rdbfread(SEXP dbfnm) { DBFHandle hDBF; int i, iRecord, nflds, nrecs, nRvar, pc=0; char labelbuff[81]; const char *pszFilename = NULL; int nWidth, nDecimals, val; char szTitle[12], buf[2]; const char *p; DBFFieldType eType; SEXP df, tmp, varlabels, row_names, DataTypes; short *types; /* -------------------------------------------------------------------- */ /* Handle arguments. */ /* -------------------------------------------------------------------- */ pszFilename = CHAR(STRING_ELT(dbfnm, 0)); /* -------------------------------------------------------------------- */ /* Open the file. */ /* -------------------------------------------------------------------- */ hDBF = DBFOpen(pszFilename, "rb" ); if( hDBF == NULL ) error(_("unable to open DBF file")); /* -------------------------------------------------------------------- */ /* If there is no data in this file let the user know. */ /* -------------------------------------------------------------------- */ if( DBFGetFieldCount(hDBF) == 0 ) { DBFClose( hDBF ); error(_("no fields in DBF table")); } nRvar = 0; nflds = DBFGetFieldCount(hDBF); nrecs = DBFGetRecordCount(hDBF); types = (short *) R_alloc(nflds, sizeof(short)); PROTECT(DataTypes = allocVector(STRSXP, nflds)); pc++; for( i = 0; i < nflds; i++ ) { eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals ); switch(eType) { case FTString: types[i] = 1; nRvar++; break; case FTInteger: types[i] = 2; nRvar++; break; case FTDouble: types[i] = 3; nRvar++; break; case FTLogical: types[i] = 4; nRvar++; break; default: /* doesn't seem to be possible */ types[i] = 0; } buf[0] = hDBF->pachFieldType[i]; buf[1] = '\0'; SET_STRING_ELT(DataTypes, i, mkChar(buf)); } PROTECT(df = allocVector(VECSXP, nRvar)); pc++; PROTECT(varlabels = allocVector(STRSXP, nRvar)); pc++; for(i = 0, nRvar = 0; i < nflds; i++) { eType = DBFGetFieldInfo( hDBF, i, szTitle, &nWidth, &nDecimals ); switch(types[i]) { case 1: SET_VECTOR_ELT(df, nRvar, allocVector(STRSXP,nrecs)); break; case 2: SET_VECTOR_ELT(df, nRvar, allocVector(INTSXP,nrecs)); break; case 3: SET_VECTOR_ELT(df, nRvar, allocVector(REALSXP,nrecs)); break; case 4: SET_VECTOR_ELT(df, nRvar, allocVector(LGLSXP,nrecs)); break; default: continue; } SET_STRING_ELT(varlabels, nRvar, mkChar(szTitle)); nRvar++; } for(iRecord = 0; iRecord < nrecs; iRecord++) { nRvar = 0; for(i = 0; i < nflds; i++) switch(types[i]) { case 1: if( DBFIsAttributeNULL( hDBF, iRecord, i )) SET_STRING_ELT(VECTOR_ELT(df, nRvar), iRecord, NA_STRING); else SET_STRING_ELT(VECTOR_ELT(df, nRvar), iRecord, mkChar(DBFReadStringAttribute( hDBF, iRecord, i))); nRvar++; break; case 2: if( DBFIsAttributeNULL( hDBF, iRecord, i )) INTEGER(VECTOR_ELT(df, nRvar))[iRecord] = NA_INTEGER; else { double dtmp = DBFReadDoubleAttribute( hDBF, iRecord, i ); if((dtmp > 2147483647.0) || (dtmp < -2147483646.0)) { int ii, *it; double *r; /* allow for NA_INTEGER = -(2^31 -1)*/ PROTECT(tmp = VECTOR_ELT(df, nRvar)); it = INTEGER(tmp); SET_VECTOR_ELT(df, nRvar, allocVector(REALSXP, nrecs)); r = REAL(VECTOR_ELT(df, nRvar)); for (ii = 0; ii < iRecord; ii++) { int itmp = it[ii]; r[ii] = (itmp == NA_INTEGER) ? NA_REAL : itmp; } UNPROTECT(1); r[iRecord] = dtmp; types[i] = 3; } else INTEGER(VECTOR_ELT(df, nRvar))[iRecord] = (int) dtmp; } nRvar++; break; case 3: if( DBFIsAttributeNULL( hDBF, iRecord, i )) REAL(VECTOR_ELT(df, nRvar))[iRecord] = NA_REAL; else REAL(VECTOR_ELT(df, nRvar))[iRecord] = DBFReadDoubleAttribute( hDBF, iRecord, i ); nRvar++; break; case 4: if( DBFIsAttributeNULL( hDBF, iRecord, i )) LOGICAL(VECTOR_ELT(df, nRvar))[iRecord] = NA_LOGICAL; else { p = DBFReadStringAttribute( hDBF, iRecord, i ); switch(*p){ case 'f': case 'F': case 'n': case 'N': val = 0; break; case 't': case 'T': case 'y': case 'Y': val = 1; break; case '?': val = NA_LOGICAL; break; default: warning(_("value |%d| found in logical field"), *p); val = NA_LOGICAL; break; } LOGICAL(VECTOR_ELT(df, nRvar))[iRecord] = val; } nRvar++; break; default: break; } } DBFClose( hDBF ); PROTECT(tmp = mkString("data.frame")); pc++; setAttrib(df, R_ClassSymbol, tmp); setAttrib(df, R_NamesSymbol, varlabels); setAttrib(df, install("data_types"), DataTypes); PROTECT(row_names = allocVector(STRSXP, nrecs)); pc++; for (i = 0; i < nrecs; i++) { sprintf(labelbuff, "%d", i+1); SET_STRING_ELT(row_names, i, mkChar(labelbuff)); } setAttrib(df, R_RowNamesSymbol, row_names); UNPROTECT(pc); return(df); }
bool ShapelibProxy::query(const std::string &handle, std::string &errorMessage, const std::string &whereClause, const std::string &labelFormat, LocationType minClip, LocationType maxClip, const CoordinateTransformation* pCoordinateTransformation) { std::map<std::string, ShapelibHandle>::iterator iter = mHandles.find(handle); if (iter == mHandles.end()) { errorMessage = "Could not find handle"; return false; } ShapelibHandle& shapelibHandle = iter->second; if (!whereClause.empty()) { errorMessage = "Shapelib does not support where clauses"; return false; } std::string formattedLabel = preprocessFormatString(shapelibHandle, labelFormat); int count = 0; ArcProxyLib::FeatureType featureType = ArcProxyLib::UNKNOWN; if (!getTypeAndCount(shapelibHandle, errorMessage, featureType, count)) { return false; } for (int i = 0; i < count; ++i) { SHPObject* pShpObject = SHPReadObject(shapelibHandle.getShpHandle(), i); if (pShpObject == NULL) { continue; } // Convert from shapefile coordinates to application coordinates. double minX = pShpObject->dfXMin; double maxX = pShpObject->dfXMax; double minY = pShpObject->dfYMin; double maxY = pShpObject->dfYMax; if (pCoordinateTransformation != NULL) { if (pCoordinateTransformation->translateShapeToApp(minX, minY, minX, minY) == false || pCoordinateTransformation->translateShapeToApp(maxX, maxY, maxX, maxY) == false) { errorMessage = "Coordinate transformation failed for bounding box. Check the .prj file and try again."; return false; } } QRectF objectRect(QPointF(minY, minX), QPointF(maxY, maxX)); QRectF clipRect(QPointF(minClip.mX, minClip.mY), QPointF(maxClip.mX, maxClip.mY)); if ((clipRect.isEmpty() == true) || ((objectRect.isEmpty() == true) && (clipRect.contains(objectRect.topLeft()) == true)) || (objectRect.intersects(clipRect) == true)) { ArcProxyLib::Feature feature; feature.setType(featureType); std::vector<std::pair<double, double> > vertices(pShpObject->nVertices); for (int vertex = 0; vertex < pShpObject->nVertices; ++vertex) { // Convert from shapefile coordinates to application coordinates. double vertexX = pShpObject->padfX[vertex]; double vertexY = pShpObject->padfY[vertex]; if (pCoordinateTransformation != NULL) { if (pCoordinateTransformation->translateShapeToApp(vertexX, vertexY, vertexX, vertexY) == false) { errorMessage = "Coordinate transformation failed for vertex. Check the .prj file and try again."; return false; } } vertices[vertex] = std::make_pair(vertexY, vertexX); } feature.setVertices(vertices); for (int path = 0; path < pShpObject->nParts; ++path) { feature.addPathAtIndex(pShpObject->panPartStart[path]); } feature.setLabel(std::for_each(formattedLabel.begin(), formattedLabel.end(), ShapelibFormatStringProcessor( shapelibHandle, i)).getProcessedString()); std::vector<std::string> attributes; int fieldCount = DBFGetFieldCount(shapelibHandle.getDbfHandle()); for (int field = 0; field < fieldCount; ++field) { std::string name; std::string type; std::string value; if (getFieldAttributes(shapelibHandle, name, type, value, field, i)) { attributes.push_back(value); } } feature.setAttributes(attributes); emit featureLoaded(feature); } SHPDestroyObject(pShpObject); } return true; }
// --------------------------------------------------------------------------- // // ----------- int bDBFTable::CountFields(){ return(DBFGetFieldCount(_dbf)); }
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); }
/////////////////////////////////////////////////////////////////////////////// // Export eines Objektes HRESULT CArcViewLayer::ExportData ( GSTRUCT *pGS, MFELD *pMF, LPCSTR pcUIdent, CArcViewLayerAttributes *pMap) { OBJECTTYPE rgType = GetType(); int iShapeId = -1; int iObjTyp = pGS -> Typ; _ASSERTE(rgType == ObjType2OBJECTTYPE(pGS -> Typ, true)); // Objekttyp muß stimmen // Geometrie erzeugen if (OBJECTTYPE_Area == rgType) { // Anzahl der Konturen feststellen und Konturfeld zusammenbauen int iKCnt = 1; vector<int> Cnts(1); int iCurr = 0; Cnts[0] = 0; for (int i = 0; 0 != pGS -> cnt[i]; ++i) { if (i > 0) Cnts.push_back(iCurr); iCurr += pGS -> cnt[i]; } iKCnt = i; _ASSERTE(iKCnt > 0 && iKCnt == Cnts.size()); // Objekt erzeugen CArcViewObject Obj(SHPCreateObject(m_nShapeType, -1, iKCnt, Cnts.begin(), NULL, pGS -> GSize, pGS -> x, pGS -> y, NULL, NULL)); iShapeId = SHPWriteObject(m_hSHP, -1, Obj); } else { // Objekt erzeugen CArcViewObject Obj(SHPCreateSimpleObject(m_nShapeType, pGS -> GSize, pGS -> x, pGS -> y, NULL)); iShapeId = SHPWriteObject(m_hSHP, -1, Obj); } if (iShapeId == -1) return E_FAIL; // Attribute sicherstellen (bei TRiAS-Datenquellen jedesmal) if (!HasFields() || DEX_GetTRiASDataSourceEx(DEX_GetObjectsProject(pGS -> Id))) { // sämtliche Attribute dieses Layers durchgehen und ggf. erzeugen for (CArcViewLayerAttributes::iterator it = pMap -> begin(); it != pMap -> end(); ++it) { // Feld in Datei erzeugen int iField = -1; CArcViewAttribute &rAttr = (*it).second; LPCSTR pcName = rAttr.GetName(); if (OBJECTTYPE_Text != m_rgType && !strcmp (pcName, g_cbLabelText)) continue; // Labeltext nur für Textobjekte if (FAILED(FieldExists (pcName, rAttr.GetTyp(), &iField))) { RETURN_FAILED_HRESULT(AddField(pcName, rAttr.GetTyp(), rAttr.GetLen(), rAttr.GetDecimals(), &iField)); } _ASSERTE(-1 != iField); // mehrerer Objekttypen eines Idents haben identischen Satz von Attributen _ASSERTE(-1 == (*it).second.GetField(iObjTyp) || (*it).second.GetField(iObjTyp) == iField || DEX_GetTRiASDataSourceEx(DEX_GetObjectsProject(pGS -> Id))); // Feldnummer beim Attribut speichern (*it).second.SetField(iField, iObjTyp); } // Textlabel für Textobjekte if (OBJECTTYPE_Text == m_rgType) { pair<CArcViewLayerAttributes::iterator, bool> p = pMap -> insert (CArcViewLayerAttributes::value_type (-1, CArcViewAttribute(g_cbLabelText, 'a', _MAX_PATH))); if (p.second) { int iField = -1; it = p.first; if (FAILED(FieldExists (g_cbLabelText, FTString, &iField))) { RETURN_FAILED_HRESULT(AddField(g_cbLabelText, FTString, _MAX_PATH, 0, &iField)); } _ASSERTE(-1 != iField); (*it).second.SetField(iField, iObjTyp); } } SetHasFields(); } // Attributwerte schreiben if (NULL != pMF) { // nur, wenn mindestens ein Attribut ausgegeben werden soll for (MFELD *pMFT = pMF; 0 != pMFT -> MCode; ++pMFT) { if (NULL != pMap) { CArcViewLayerAttributes::iterator it = pMap -> find (pMFT -> MCode); _ASSERTE(it != pMap -> end()); // Attribut sollte (jetzt) existieren if (it != pMap -> end()) { // Feld muß bereits erzeugt worden sein und Typ muß mit DBF übereinstimmen int iField = (*it).second.GetField(iObjTyp); _ASSERTE(-1 != iField); _ASSERTE((*it).second.GetTyp() == DBFGetFieldInfo (m_hDBF, iField, NULL, NULL, NULL)); // Wert je nach Typ in die Datenbank schreiben switch ((*it).second.GetTyp()) { case FTString: { char cbBuffer[_MAX_PATH] = { '\0' }; if (NULL != pMFT -> MText) OemToCharBuff(pMFT -> MText, cbBuffer, min(MAX_DBASEFIELD_LEN, strlen(pMFT -> MText))+1); // '\0' mit konvertieren DBFWriteStringAttribute(m_hDBF, iShapeId, iField, cbBuffer); } break; case FTInteger: DBFWriteIntegerAttribute(m_hDBF, iShapeId, iField, (NULL != pMFT -> MText) ? atol(pMFT -> MText) : 0); break; case FTDouble: DBFWriteDoubleAttribute(m_hDBF, iShapeId, iField, (NULL != pMFT -> MText) ? atof(pMFT -> MText) : 0.0); break; } } } else { _ASSERTE(NULL != pMap); // eigentlich sollte eine Map da sein // keine Map, also erstmal leeren Datensatz schreiben int iCnt = DBFGetFieldCount(m_hDBF); for (int i = 0; i < iCnt; ++i) { switch (DBFGetFieldInfo(m_hDBF, i, NULL, NULL, NULL)) { case FTString: DBFWriteStringAttribute(m_hDBF, iShapeId, i, g_cbNil); break; case FTInteger: DBFWriteIntegerAttribute(m_hDBF, iShapeId, i, 0); break; case FTDouble: DBFWriteDoubleAttribute(m_hDBF, iShapeId, i, 0.0); break; } } } } } return S_OK; }