Beispiel #1
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;
}
Beispiel #2
0
bool ShapelibProxy::getFieldAttributes(const ShapelibHandle &handle, std::string &name,
                                       std::string &type, std::string &value, int field, int feature)
{
   char cname[12]; // defined as maximum length
   DBFFieldType fieldType = DBFGetFieldInfo(handle.getDbfHandle(), field, cname, NULL, NULL);
   
   name = cname;

   switch (fieldType)
   {
   case FTString:
      type = "String";
      value = DBFReadStringAttribute(handle.getDbfHandle(), feature, field);
      break;
   case FTInteger:
      type = "Integer";
      value = boost::lexical_cast<std::string>(
         DBFReadIntegerAttribute(handle.getDbfHandle(), feature, field));
      break;
   case FTDouble:
      type = "Double";
      value = boost::lexical_cast<std::string>(
         DBFReadDoubleAttribute(handle.getDbfHandle(), feature, field));
      break;
   default:
      type = "Unknown";
      value = "[Error: Not stringable]";
      return false;
   }

   return true;
}
Beispiel #3
0
/* Compare our assumed "primary key", or identifying record */
bool compareDBFkey(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;

        if( identifyKey >= 0 )
        {
            i = identifyKey;
            j = columnMatchArray[i];

            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 );
            temp = memcmp ( &iBuffer, &jBuffer, nWidth );
            if( temp )
                result = true;
        }
        return( result );
}
Beispiel #4
0
///////////////////////////////////////////////////////////////////////////////
// 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
}
Beispiel #5
0
int selectrec()
{
    long int value, ty;

    ty = DBFGetFieldInfo( hDBF, iselectitem, NULL, &iWidth, &iDecimals);
    switch(ty)
    {
      case FTString:
        puts("Invalid Item");
        iselect=FALSE;
	break;
      case FTInteger:
        value = DBFReadIntegerAttribute( hDBF, iRecord, iselectitem );
        for (j = 0; j<selcount; j++)
        {
            if (selectvalues[j] == value)
            {
                if (iunselect) return(0);  /* Keep this record */
                else  return(1);  /* Skip this record */
            }
        }
	break;
      case FTDouble:
        puts("Invalid Item");
        iselect=FALSE;
        break;
    }
    if (iunselect) return(1);  /* Skip this record */
    else  return(0);  /* Keep this record */
}
Beispiel #6
0
    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);
    }
// ---------------------------------------------------------------------------
// 
// -----------
int	bDBFTable::FieldSign(int f, int* sign){
char	dbfnam[256];
int		dbflen;
int		dbfdecs;
int		dbfsgn=DBFGetFieldInfo(_dbf,f-1,dbfnam,&dbflen,&dbfdecs); 
	*sign=dbf2db(dbfsgn);
	return(0);
}
Beispiel #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 );
}
Beispiel #9
0
///////////////////////////////////////////////////////////////////////////////
// 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
}
Beispiel #10
0
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 );
}
Beispiel #11
0
extern Tcl_Obj *
Dbf_NewFieldObj (DBFHandle const dbfHandle, int const field)
{
  char fieldName[12];
  int length;
  Tcl_Obj *fieldPtr;

  DBFGetFieldInfo (dbfHandle, field, fieldName, 0, 0);
  length = strlen (fieldName);
  fieldPtr = Tcl_NewObj ();
  fieldPtr->typePtr = &dbfFieldType;
  fieldPtr->bytes = ckalloc (length + 1);
  memcpy (fieldPtr->bytes, fieldName, length + 1);
  fieldPtr->length = length;
  SetDBFHandle (fieldPtr, dbfHandle);
  SetFieldIndex (fieldPtr, field);
  return fieldPtr;
}
Beispiel #12
0
static Tcl_Obj *
NewAttributeObj (DBFHandle const dbfHandle, int const record, int const field)
{
  if (DBFIsAttributeNULL (dbfHandle, record, field))
    {
      return Tcl_NewObj ();
    }
  switch (DBFGetFieldInfo (dbfHandle, field, NULL, NULL, NULL))
    {
    case FTInteger:
      return Tcl_NewIntObj (DBFReadIntegerAttribute (dbfHandle, record, field));
    case FTDouble:
      return
        Tcl_NewDoubleObj (DBFReadDoubleAttribute (dbfHandle, record, field));
    default:
      return
        Tcl_NewStringObj (DBFReadStringAttribute (dbfHandle, record, field),
                          -1);
    }
}
Beispiel #13
0
void findselect()
{
    /* Find the select field name */
    iselectitem = -1;
    for( i = 0; i < ti  &&  iselectitem < 0; i++ )
    {
	iType = DBFGetFieldInfo( hDBF, i, iszTitle, &iWidth, &iDecimals );
        if (strncasecmp2(iszTitle, selectitem, 0) == 0) iselectitem = i;
    }
    if (iselectitem == -1) 
    {
        printf("Warning: Item not found for selection (%s)\n",selectitem);
        iselect = FALSE;
        iall = FALSE;
	showitems();
        printf("Continued... (Selecting entire file)\n");
    }
    /* Extract all of the select values (by field type) */
    
}
Beispiel #14
0
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);
}
// ---------------------------------------------------------------------------
// 
// -----------
int	bDBFTable::FieldSize(int f, int* sz){
char	dbfnam[256];
int		dbflen;
int		dbfdecs;
int		dbfsgn=DBFGetFieldInfo(_dbf,f-1,dbfnam,&dbflen,&dbfdecs); 
	
	switch(dbfsgn){
		case FTString:
			*sz=dbflen+1;
			break;
		case FTInteger:
			*sz=sizeof(int);
			break;
		case FTDouble:
			*sz=sizeof(double);
			break;
		default:
			*sz=0;
			break;
	}
	return(0);
}
Beispiel #16
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);
}
Beispiel #17
0
static void
SetAttributeObj (Tcl_Obj * const objPtr, DBFHandle const dbfHandle,
                 int const record, int const field)
{
  if (DBFIsAttributeNULL (dbfHandle, record, field))
    {
      return;
    }
  switch (DBFGetFieldInfo (dbfHandle, field, NULL, NULL, NULL))
    {
    case FTInteger:
      Tcl_SetIntObj (objPtr,
                     DBFReadIntegerAttribute (dbfHandle, record, field));
      break;
    case FTDouble:
      Tcl_SetDoubleObj (objPtr,
                        DBFReadDoubleAttribute (dbfHandle, record, field));
      break;
    default:
      Tcl_SetStringObj (objPtr,
                        DBFReadStringAttribute (dbfHandle, record, field), -1);
    }
}
Beispiel #18
0
/* -------------------------------------------------------------------- */
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 );
            }
        }
}
Beispiel #19
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");
}
Beispiel #20
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 );
}
Beispiel #21
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;
}
Beispiel #22
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;
}
Beispiel #23
0
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;
}
Beispiel #24
0
void dibSHP::procesFile(Document_Interface *doc)
{
    int num_ent, st;
    double min_bound[4], max_bound[4];

    currDoc = doc;

    QFileInfo fi = QFileInfo(fileedit->text());
    if (fi.suffix() != "shp") {
        QMessageBox::critical ( this, "Shapefile", QString(tr("The file %1 not have extension .shp")).arg(fileedit->text()) );
        return;
    }

    if (!fi.exists() ) {
        QMessageBox::critical ( this, "Shapefile", QString(tr("The file %1 not exist")).arg(fileedit->text()) );
        return;
    }

    QString file = fi.canonicalFilePath ();

    SHPHandle sh = SHPOpen( file.toLocal8Bit(), "rb" );
    SHPGetInfo( sh, &num_ent, &st, min_bound, max_bound );
    DBFHandle dh = DBFOpen( file.toLocal8Bit(), "rb" );

    if (radiolay1->isChecked()) {
        layerF = -1;
        attdata.layer = currDoc->getCurrentLayer();
    } else {
        layerF = DBFGetFieldIndex( dh, (layerdata->currentText()).toLatin1().data() );
        layerT = DBFGetFieldInfo( dh, layerF, NULL, NULL, NULL );
    }
    if (radiocol1->isChecked())
        colorF = -1;
    else {
        colorF = DBFGetFieldIndex( dh, (colordata->currentText()).toLatin1().data() );
        colorT = DBFGetFieldInfo( dh, colorF, NULL, NULL, NULL );
    }
    if (radioltype1->isChecked())
        ltypeF = -1;
    else {
        ltypeF = DBFGetFieldIndex( dh, (ltypedata->currentText()).toLatin1().data() );
        ltypeT = DBFGetFieldInfo( dh, ltypeF, NULL, NULL, NULL );
    }
    if (radiolwidth1->isChecked())
        lwidthF = -1;
    else {
        lwidthF = DBFGetFieldIndex( dh, (lwidthdata->currentText()).toLatin1().data() );
        lwidthT = DBFGetFieldInfo( dh, lwidthF, NULL, NULL, NULL );
    }
    if (radiopoint1->isChecked())
        pointF = -1;
    else {
        pointF = DBFGetFieldIndex( dh, (pointdata->currentText()).toLatin1().data() );
        pointT = DBFGetFieldInfo( dh, pointF, NULL, NULL, NULL );
    }

    currlayer =currDoc->getCurrentLayer();
    for( int i = 0; i < num_ent; i++ ) {
        sobject= NULL;
        sobject = SHPReadObject( sh, i );
        if (sobject) {
            switch (sobject->nSHPType) {
            case SHPT_NULL:
                break;
            case SHPT_POINT:
            case SHPT_POINTM: //2d point with measure
            case SHPT_POINTZ: //3d point
                readPoint(dh, i);
                break;
            case SHPT_MULTIPOINT:
            case SHPT_MULTIPOINTM:
            case SHPT_MULTIPOINTZ:
                break;
            case SHPT_ARC:
            case SHPT_ARCM:
            case SHPT_ARCZ:
                readPolyline(dh, i);
                break;
            case SHPT_POLYGON:
            case SHPT_POLYGONM:
            case SHPT_POLYGONZ:
                readPolylineC(dh, i);
            case SHPT_MULTIPATCH:
                readMultiPolyline(dh, i);
            default:
                break;
            }
            SHPDestroyObject(sobject);
        }
    }

    SHPClose( sh );
    DBFClose( dh );
    currDoc->setLayer(currlayer);
}
bool rspfShapeDatabase::getRecord(rspfShapeDatabaseRecord& result)
{
    if(isOpen()&&( (theRecordNumber < theHandle->nRecords) ))
    {
        if(result.getNumberOfFields() != theHandle->nFields)
        {
            result.setNumberOfFields(theHandle->nFields);
        }

        char name[1024] = {'\0'};
        int width       = 0;
        int decimals    = 0;
        int iField      = 0;
        std::vector<int>         fieldWidths;

        for(iField = 0; iField < theHandle->nFields; ++iField)
        {
            DBFFieldType fieldType = DBFGetFieldInfo(theHandle,
                                     iField,
                                     name,
                                     &width,
                                     &decimals);
            rspfShapeDatabaseField field;
            field.theName = name;
            field.theWidth = width;
            field.theDecimals = decimals;
            field.theFieldType = fieldType;

            rspfString key = "field";
            key+=rspfString::toString(iField+1);
            key+=(rspfString(".")+name+":");

            switch(fieldType)
            {
            case FTString:
            {
                field.theValue = DBFReadStringAttribute(theHandle, theRecordNumber, iField);
                break;
            }
            case FTInteger:
            {
                field.theValue = rspfString::toString(DBFReadIntegerAttribute(theHandle, theRecordNumber, iField));
                break;
            }
            case FTDouble:
            {
                field.theValue = rspfString::toString(DBFReadDoubleAttribute(theHandle, theRecordNumber, iField));
                break;
            }
            case FTLogical:
            {
                break;
            }
            case FTInvalid:
            {
                break;
            }
            }
            result.setField(field,
                            iField);
        }
        return true;
    }
    return false;
}
Beispiel #26
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 );
}
Beispiel #27
0
int main (int argc, char *argv[]) {

  SHPHandle  inSHP, outSHP;
  DBFHandle  inDBF, outDBF;
  int        len; 
  int        i;
  char       **fieldNames;
  char       **strOrder = 0;
  struct DataStruct *index;
  int        width;
  int        decimals;
  SHPObject  *feat;
  void       *tuple;

  if (argc < 4) {
    printf("USAGE: shpsort <infile> <outfile> <field[;...]> [<(ASCENDING|DESCENDING)[;...]>]\n");
    exit(EXIT_FAILURE);
  }

  inSHP = SHPOpen (argv[1], "rb");
  if (!inSHP) {
    fputs("Couldn't open shapefile for reading!\n", stderr);
    exit(EXIT_FAILURE);
  }
  SHPGetInfo(inSHP, &nShapes, &shpType, NULL, NULL);

  /* If we can open the inSHP, open its DBF */
  inDBF = DBFOpen (argv[1], "rb");
  if (!inDBF) {
    fputs("Couldn't open dbf file for reading!\n", stderr);
    exit(EXIT_FAILURE);
  }

  /* Parse fields and validate existence */
  fieldNames = split(argv[3], ";");
  if (!fieldNames) {
    fputs("ERROR: parsing field names!\n", stderr);
    exit(EXIT_FAILURE);
  }
  for (nFields = 0; fieldNames[nFields] ; nFields++) {
    continue;
  }

  fldIdx = malloc(sizeof *fldIdx * nFields);
  if (!fldIdx) {
    fputs("malloc failed!\n", stderr);
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < nFields; i++) {
    len = (int)strlen(fieldNames[i]);
    while(len > 0) {
      --len;
      fieldNames[i][len] = (char)toupper((unsigned char)fieldNames[i][len]); 
    }
    fldIdx[i] = DBFGetFieldIndex(inDBF, fieldNames[i]);
    if (fldIdx[i] < 0) {
      /* try "SHAPE" */
      if (strcmp(fieldNames[i], "SHAPE") == 0) {
	fldIdx[i] = -1;
      }
      else if (strcmp(fieldNames[i], "FID") == 0) {
	fldIdx[i] = -2;
      }
      else {
	fprintf(stderr, "ERROR: field '%s' not found!\n", fieldNames[i]);
	exit(EXIT_FAILURE);
      }
    }
  }


  /* set up field type array */
  fldType = malloc(sizeof *fldType * nFields);
  if (!fldType) {
    fputs("malloc failed!\n", stderr);
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < nFields; i++) {
    if (fldIdx[i] < 0) {
      fldType[i] = fldIdx[i];
    }
    else {
      fldType[i] = DBFGetFieldInfo(inDBF, fldIdx[i], NULL, &width, &decimals);
      if (fldType[i] == FTInvalid) {
	fputs("Unrecognized field type in dBASE file!\n", stderr);
	exit(EXIT_FAILURE);
      }
    }
  }


  /* set up field order array */
  fldOrder = malloc(sizeof *fldOrder * nFields);
  if (!fldOrder) {
    fputs("malloc failed!\n", stderr);
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < nFields; i++) {
    /* default to ascending order */
    fldOrder[i] = ASCENDING;
  }
  if (argc > 4) {
    strOrder = split(argv[4], ";");
    if (!strOrder) {
      fputs("ERROR: parsing fields ordering!\n", stderr);
      exit(EXIT_FAILURE);
    }
    for (i = 0; i < nFields && strOrder[i]; i++) {
      if (strcmp(strOrder[i], "DESCENDING") == 0) {
	fldOrder[i] = DESCENDING;
      }
    }
  }

  /* build the index */
  index = build_index (inSHP, inDBF);

  /* Create output shapefile */
  outSHP = SHPCreate(argv[2], shpType);
  if (!outSHP) {
    fprintf(stderr, "%s:%d: couldn't create output shapefile!\n",
	    __FILE__, __LINE__);
    exit(EXIT_FAILURE);
  }
  
  /* Create output dbf */
  outDBF = DBFCloneEmpty(inDBF, argv[2]);
  if (!outDBF) {
    fprintf(stderr, "%s:%d: couldn't create output dBASE file!\n",
	    __FILE__, __LINE__);
    exit(EXIT_FAILURE);
  }

  /* Copy projection file, if any */
  copy_related(argv[1], argv[2], ".shp", ".prj");

  /* Copy metadata file, if any */
  copy_related(argv[1], argv[2], ".shp", ".shp.xml");

  /* Write out sorted results */
  for (i = 0; i < nShapes; i++) {
    feat = SHPReadObject(inSHP, index[i].record);
    if (SHPWriteObject(outSHP, -1, feat) < 0) {
      fprintf(stderr, "%s:%d: error writing shapefile!\n", __FILE__, __LINE__);
      exit(EXIT_FAILURE);
    }
    tuple = (void *) DBFReadTuple(inDBF, index[i].record);
    if (DBFWriteTuple(outDBF, i, tuple) < 0) {
      fprintf(stderr, "%s:%d: error writing dBASE file!\n", __FILE__, __LINE__);
      exit(EXIT_FAILURE);
    }
  }
  SHPClose(inSHP);
  SHPClose(outSHP);
  DBFClose(inDBF);
  DBFClose(outDBF);

  return EXIT_SUCCESS;

}
Beispiel #28
0
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;
    }
}
std::ostream& rspfShapeDatabase::print(std::ostream& out)const
{
    if(isOpen())
    {
        out << std::setw(15)<<setiosflags(std::ios::left)
            <<"DB filename:" << theFilename << std::endl
            << std::setw(15)<<setiosflags(std::ios::left)
            <<"records:" << theHandle->nRecords << std::endl
            << std::setw(15)<<setiosflags(std::ios::left)
            <<"fields:" << theHandle->nFields << std::endl;
        char name[1024] = {'\0'};
        int width       = 0;
        int decimals    = 0;
        int iField      = 0;
        std::vector<int>         fieldWidths;

        for(iField = 0; iField < theHandle->nFields; ++iField)
        {
            DBFFieldType fieldType = DBFGetFieldInfo(theHandle,
                                     iField,
                                     name,
                                     &width,
                                     &decimals);
            rspfString s = "field " + rspfString::toString(iField+1) + " name:";
            switch(fieldType)
            {
            case FTString:
            case FTInteger:
            case FTDouble:
            {
                out << std::setw(15) << setiosflags(std::ios::left) << s.c_str() << name << std::endl;
                break;
            }
            default:
            {
                out << std::setw(15) << setiosflags(std::ios::left) << s.c_str() << "INVALID"<<std::endl;
                break;
            }
            }
        }
        for(int iShape = 0; iShape < theHandle->nRecords; ++iShape)
        {
            for(iField = 0; iField < theHandle->nFields; ++iField)
            {
                DBFFieldType fieldType = DBFGetFieldInfo(theHandle,
                                         iField,
                                         name,
                                         &width,
                                         &decimals);

                rspfString key = "field";
                key+=rspfString::toString(iField+1);
                key+=(rspfString(".")+name+":");

                switch(fieldType)
                {
                case FTString:
                {

                    out << std::setw(25) << setiosflags(std::ios::left) << key.c_str()
                        << DBFReadStringAttribute(theHandle, iShape, iField) <<std::endl;

                    break;
                }
                case FTInteger:
                {
                    out << std::setw(25) << setiosflags(std::ios::left) << key.c_str()
                        << DBFReadIntegerAttribute(theHandle, iShape, iField) << std::endl;

                    break;
                }
                case FTDouble:
                {
                    out << std::setw(25) << setiosflags(std::ios::left) << key.c_str()
                        << DBFReadDoubleAttribute(theHandle, iShape, iField) << std::endl;

                    break;
                }
                case FTLogical:
                {
                    break;
                }
                case FTInvalid:
                {
                    break;
                }
                }
            }
            out << "_________________________________"<<std::endl;
        }
    }
    return out;
}
Beispiel #30
0
///////////////////////////////////////////////////////////////////////////////
// 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;
}