void TigerFileBase::EstablishFeatureCount() { if( fpPrimary == NULL ) return; nRecordLength = EstablishRecordLength( fpPrimary ); if( nRecordLength == -1 ) { nRecordLength = 1; nFeatures = 0; return; } /* -------------------------------------------------------------------- */ /* Now we think we know the fixed record length for the file */ /* (including line terminators). Get the total file size, and */ /* divide by this length to get the presumed number of records. */ /* -------------------------------------------------------------------- */ long nFileSize; VSIFSeek( fpPrimary, 0, SEEK_END ); nFileSize = VSIFTell( fpPrimary ); if( (nFileSize % nRecordLength) != 0 ) { CPLError( CE_Warning, CPLE_FileIO, "TigerFileBase::EstablishFeatureCount(): " "File length %d doesn't divide by record length %d.\n", (int) nFileSize, (int) nRecordLength ); } nFeatures = nFileSize / nRecordLength; }
OGRErr OGRMILayerAttrIndex::LoadConfigFromXML() { FILE *fp; int nXMLSize; char *pszRawXML; CPLAssert( poINDFile == NULL ); /* -------------------------------------------------------------------- */ /* Read the XML file. */ /* -------------------------------------------------------------------- */ fp = VSIFOpen( pszMetadataFilename, "rb" ); if( fp == NULL ) return OGRERR_NONE; VSIFSeek( fp, 0, SEEK_END ); nXMLSize = VSIFTell( fp ); VSIFSeek( fp, 0, SEEK_SET ); pszRawXML = (char *) CPLMalloc(nXMLSize+1); pszRawXML[nXMLSize] = '\0'; VSIFRead( pszRawXML, nXMLSize, 1, fp ); VSIFClose( fp ); OGRErr eErr = LoadConfigFromXML(pszRawXML); CPLFree(pszRawXML); return eErr; }
/*! \brief Read the file & load the data \param pszFile pointer to a filename \return TRUE on success \return FALSE on error */ int VFKReader::LoadData() { FILE *fp; long nLength; if (m_pszFilename == NULL) return FALSE; /* load vfk file */ fp = VSIFOpen(m_pszFilename, "rb"); if (fp == NULL) { CPLError(CE_Failure, CPLE_OpenFailed, "Failed to open file %s.", m_pszFilename); return FALSE; } /* get file length */ VSIFSeek(fp, 0, SEEK_END); nLength = VSIFTell(fp); VSIFSeek(fp, 0, SEEK_SET); /* read file - is necessary to read the whole file? */ m_pszWholeText = (char *) VSIMalloc(nLength+1); if (m_pszWholeText == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Failed to allocate %ld byte buffer for %s,\n" "is this really a VFK file?", nLength, m_pszFilename); VSIFClose(fp); return FALSE; } if (VSIFRead(m_pszWholeText, nLength, 1, fp) != 1) { VSIFree(m_pszWholeText); m_pszWholeText = NULL; VSIFClose(fp); CPLError(CE_Failure, CPLE_AppDefined, "Read failed on %s.", m_pszFilename); return FALSE; } m_pszWholeText[nLength] = '\0'; VSIFClose(fp); /* split lines */ /* TODO: reduce chars */ for (char *poChar = m_pszWholeText; *poChar != '\0'; poChar++) { if (*poChar == '\244' && *(poChar+1) != '\0' && *(poChar+2) != '\0') { *(poChar++) = ' '; // \r *(poChar++) = ' '; // \n *poChar = ' '; } } CPLDebug("OGR_VFK", "VFKReader::LoadData(): length=%ld", nLength); return TRUE; }
int OGRFMECacheIndex::Load() { /* -------------------------------------------------------------------- */ /* Lock the cache index file if not already locked. */ /* -------------------------------------------------------------------- */ if( hLock == NULL && !Lock() ) return FALSE; if( psTree != NULL ) { CPLDestroyXMLNode( psTree ); psTree = NULL; } /* -------------------------------------------------------------------- */ /* Open the index file. If we don't get it, we assume it is */ /* because it doesn't exist, and we create a "stub" tree in */ /* memory. */ /* -------------------------------------------------------------------- */ FILE *fpIndex; int nLength; char *pszIndexBuffer; fpIndex = VSIFOpen( GetPath(), "rb" ); if( fpIndex == NULL ) { psTree = CPLCreateXMLNode( NULL, CXT_Element, "OGRFMECacheIndex" ); return TRUE; } /* -------------------------------------------------------------------- */ /* Load the data from the file. */ /* -------------------------------------------------------------------- */ VSIFSeek( fpIndex, 0, SEEK_END ); nLength = VSIFTell( fpIndex ); VSIFSeek( fpIndex, 0, SEEK_SET ); pszIndexBuffer = (char *) CPLMalloc(nLength+1); if( (int) VSIFRead( pszIndexBuffer, 1, nLength, fpIndex ) != nLength ) { CPLError( CE_Failure, CPLE_FileIO, "Read of %d byte index file failed.", nLength ); return FALSE; } VSIFClose( fpIndex ); /* -------------------------------------------------------------------- */ /* Parse the result into an inmemory XML tree. */ /* -------------------------------------------------------------------- */ pszIndexBuffer[nLength] = '\0'; psTree = CPLParseXMLString( pszIndexBuffer ); CPLFree( pszIndexBuffer ); return psTree != NULL; }
GDALDataset *COSARDataset::Open( GDALOpenInfo * pOpenInfo ) { long nRTNB; /* Check if we're actually a COSAR data set. */ if( pOpenInfo->nHeaderBytes < 4 ) return NULL; if (!EQUALN((char *)pOpenInfo->pabyHeader+MAGIC1_OFFSET, "CSAR",4)) return NULL; /* -------------------------------------------------------------------- */ /* Confirm the requested access is supported. */ /* -------------------------------------------------------------------- */ if( pOpenInfo->eAccess == GA_Update ) { CPLError( CE_Failure, CPLE_NotSupported, "The COSAR driver does not support update access to existing" " datasets.\n" ); return NULL; } /* this is a cosar dataset */ COSARDataset *pDS; pDS = new COSARDataset(); /* steal fp */ pDS->fp = pOpenInfo->fp; pOpenInfo->fp = NULL; /* Calculate the file size */ VSIFSeek(pDS->fp,0,SEEK_END); pDS->nSize = VSIFTell(pDS->fp); VSIFSeek(pDS->fp, RS_OFFSET, SEEK_SET); VSIFRead(&pDS->nRasterXSize, 1, 4, pDS->fp); #ifdef CPL_LSB pDS->nRasterXSize = CPL_SWAP32(pDS->nRasterXSize); #endif VSIFRead(&pDS->nRasterYSize, 1, 4, pDS->fp); #ifdef CPL_LSB pDS->nRasterYSize = CPL_SWAP32(pDS->nRasterYSize); #endif VSIFSeek(pDS->fp, RTNB_OFFSET, SEEK_SET); VSIFRead(&nRTNB, 1, 4, pDS->fp); #ifdef CPL_LSB nRTNB = CPL_SWAP32(nRTNB); #endif /* Add raster band */ pDS->SetBand(1, new COSARRasterBand(pDS, nRTNB)); return pDS; }
void WCTSGetCapabilities( CPLXMLNode *psOperation ) { /* -------------------------------------------------------------------- */ /* Verify the service. */ /* -------------------------------------------------------------------- */ if( !EQUAL(CPLGetXMLValue(psOperation,"service","WCTS"),"WCTS") ) { WCTSEmitServiceException( CPLSPrintf( "Attempt to GetCapabilities for unsupported '%.500s'\n" "service. Only WCTS supported.", CPLGetXMLValue(psOperation,"service","WCTS") ) ); } /* -------------------------------------------------------------------- */ /* Search for our capabilities document. */ /* -------------------------------------------------------------------- */ const char *pszCapFilename; FILE *fp; pszCapFilename = CPLFindFile( "gdal", "wcts_capabilities.xml.0.1.0" ); if( pszCapFilename == NULL || (fp = VSIFOpen( pszCapFilename, "rt")) == NULL ) { WCTSEmitServiceException( "WCTS server misconfigured, " "unable to find capabilities document." ); } /* -------------------------------------------------------------------- */ /* Emit the document. */ /* -------------------------------------------------------------------- */ int nLen; char *pszDoc; VSIFSeek( fp, 0, SEEK_END ); nLen = VSIFTell( fp ); VSIFSeek( fp, 0, SEEK_SET ); pszDoc = (char *) CPLMalloc(nLen); VSIFRead( pszDoc, 1, nLen, fp ); VSIFClose( fp ); printf( "Content-type: text/xml%c%c", 10, 10 ); VSIFWrite( pszDoc, 1, nLen, stdout ); fflush( stdout ); CPLFree( pszDoc ); exit( 0 ); }
int ILI1Reader::AddIliGeom(OGRFeature *feature, int iField, long fpos) { #if defined(_WIN32) || defined(__WIN32__) //Other positions on Windows !? #else long nBlockLen = VSIFTell( fpItf )-fpos; VSIFSeek( fpItf, fpos, SEEK_SET ); char *pszRawData = (char *) CPLMalloc(nBlockLen+1); if( (int) VSIFRead( pszRawData, 1, nBlockLen, fpItf ) != nBlockLen ) { CPLFree( pszRawData ); CPLError( CE_Failure, CPLE_FileIO, "Read of transfer file failed." ); return FALSE; } pszRawData[nBlockLen]= '\0'; feature->SetField(iField, pszRawData); CPLFree( pszRawData ); #endif return TRUE; }
GDALDataset *RIKDataset::Open( GDALOpenInfo * poOpenInfo ) { if( poOpenInfo->fp == NULL || poOpenInfo->nHeaderBytes < 50 ) return NULL; bool rik3header = false; if( EQUALN((const char *) poOpenInfo->pabyHeader, "RIK3", 4) ) { rik3header = true; } if( rik3header ) VSIFSeek( poOpenInfo->fp, 4, SEEK_SET ); else VSIFSeek( poOpenInfo->fp, 0, SEEK_SET ); /* -------------------------------------------------------------------- */ /* Read the map name. */ /* -------------------------------------------------------------------- */ char name[1024]; GUInt16 nameLength = GetRikString( poOpenInfo->fp, name, sizeof(name) ); if( nameLength > sizeof(name) - 1 ) { return NULL; } if( !rik3header ) { if( nameLength == 0 || nameLength != strlen(name) ) return NULL; } /* -------------------------------------------------------------------- */ /* Read the header. */ /* -------------------------------------------------------------------- */ RIKHeader header; double metersPerPixel; const char *headerType = "RIK3"; if( rik3header ) { /* -------------------------------------------------------------------- */ /* RIK3 header. */ /* -------------------------------------------------------------------- */ // Read projection name char projection[1024]; GUInt16 projLength = GetRikString( poOpenInfo->fp, projection, sizeof(projection) ); if( projLength > sizeof(projection) - 1 ) { // Unreasonable string length, assume wrong format return NULL; } // Read unknown string projLength = GetRikString( poOpenInfo->fp, projection, sizeof(projection) ); // Read map north edge char tmpStr[16]; GUInt16 tmpLength = GetRikString( poOpenInfo->fp, tmpStr, sizeof(tmpStr) ); if( tmpLength > sizeof(tmpStr) - 1 ) { // Unreasonable string length, assume wrong format return NULL; } header.fNorth = atof( tmpStr ); // Read map west edge tmpLength = GetRikString( poOpenInfo->fp, tmpStr, sizeof(tmpStr) ); if( tmpLength > sizeof(tmpStr) - 1 ) { // Unreasonable string length, assume wrong format return NULL; } header.fWest = atof( tmpStr ); // Read binary values VSIFRead( &header.iScale, 1, sizeof(header.iScale), poOpenInfo->fp ); VSIFRead( &header.iMPPNum, 1, sizeof(header.iMPPNum), poOpenInfo->fp ); VSIFRead( &header.iBlockWidth, 1, sizeof(header.iBlockWidth), poOpenInfo->fp ); VSIFRead( &header.iBlockHeight, 1, sizeof(header.iBlockHeight), poOpenInfo->fp ); VSIFRead( &header.iHorBlocks, 1, sizeof(header.iHorBlocks), poOpenInfo->fp ); VSIFRead( &header.iVertBlocks, 1, sizeof(header.iVertBlocks), poOpenInfo->fp ); #ifdef CPL_MSB CPL_SWAP32PTR( &header.iScale ); CPL_SWAP32PTR( &header.iMPPNum ); CPL_SWAP32PTR( &header.iBlockWidth ); CPL_SWAP32PTR( &header.iBlockHeight ); CPL_SWAP32PTR( &header.iHorBlocks ); CPL_SWAP32PTR( &header.iVertBlocks ); #endif VSIFRead( &header.iBitsPerPixel, 1, sizeof(header.iBitsPerPixel), poOpenInfo->fp ); VSIFRead( &header.iOptions, 1, sizeof(header.iOptions), poOpenInfo->fp ); header.iUnknown = header.iOptions; VSIFRead( &header.iOptions, 1, sizeof(header.iOptions), poOpenInfo->fp ); header.fSouth = header.fNorth - header.iVertBlocks * header.iBlockHeight * header.iMPPNum; header.fEast = header.fWest + header.iHorBlocks * header.iBlockWidth * header.iMPPNum; metersPerPixel = header.iMPPNum; } else { /* -------------------------------------------------------------------- */ /* Old RIK header. */ /* -------------------------------------------------------------------- */ VSIFRead( &header.iUnknown, 1, sizeof(header.iUnknown), poOpenInfo->fp ); VSIFRead( &header.fSouth, 1, sizeof(header.fSouth), poOpenInfo->fp ); VSIFRead( &header.fWest, 1, sizeof(header.fWest), poOpenInfo->fp ); VSIFRead( &header.fNorth, 1, sizeof(header.fNorth), poOpenInfo->fp ); VSIFRead( &header.fEast, 1, sizeof(header.fEast), poOpenInfo->fp ); VSIFRead( &header.iScale, 1, sizeof(header.iScale), poOpenInfo->fp ); VSIFRead( &header.iMPPNum, 1, sizeof(header.iMPPNum), poOpenInfo->fp ); #ifdef CPL_MSB CPL_SWAP64PTR( &header.fSouth ); CPL_SWAP64PTR( &header.fWest ); CPL_SWAP64PTR( &header.fNorth ); CPL_SWAP64PTR( &header.fEast ); CPL_SWAP32PTR( &header.iScale ); CPL_SWAP32PTR( &header.iMPPNum ); #endif if (!CPLIsFinite(header.fSouth) | !CPLIsFinite(header.fWest) | !CPLIsFinite(header.fNorth) | !CPLIsFinite(header.fEast)) return NULL; bool offsetBounds; offsetBounds = header.fSouth < 4000000; header.iMPPDen = 1; if( offsetBounds ) { header.fSouth += 4002995; header.fNorth += 5004000; header.fWest += 201000; header.fEast += 302005; VSIFRead( &header.iMPPDen, 1, sizeof(header.iMPPDen), poOpenInfo->fp ); #ifdef CPL_MSB CPL_SWAP32PTR( &header.iMPPDen ); #endif headerType = "RIK1"; } else { headerType = "RIK2"; } metersPerPixel = header.iMPPNum / double(header.iMPPDen); VSIFRead( &header.iBlockWidth, 1, sizeof(header.iBlockWidth), poOpenInfo->fp ); VSIFRead( &header.iBlockHeight, 1, sizeof(header.iBlockHeight), poOpenInfo->fp ); VSIFRead( &header.iHorBlocks, 1, sizeof(header.iHorBlocks), poOpenInfo->fp ); #ifdef CPL_MSB CPL_SWAP32PTR( &header.iBlockWidth ); CPL_SWAP32PTR( &header.iBlockHeight ); CPL_SWAP32PTR( &header.iHorBlocks ); #endif if(( header.iBlockWidth > 2000 ) || ( header.iBlockWidth < 10 ) || ( header.iBlockHeight > 2000 ) || ( header.iBlockHeight < 10 )) return NULL; if( !offsetBounds ) { VSIFRead( &header.iVertBlocks, 1, sizeof(header.iVertBlocks), poOpenInfo->fp ); #ifdef CPL_MSB CPL_SWAP32PTR( &header.iVertBlocks ); #endif } if( offsetBounds || !header.iVertBlocks ) { header.iVertBlocks = (GUInt32) ceil( (header.fNorth - header.fSouth) / (header.iBlockHeight * metersPerPixel) ); } #if RIK_HEADER_DEBUG CPLDebug( "RIK", "Original vertical blocks %d\n", header.iVertBlocks ); #endif VSIFRead( &header.iBitsPerPixel, 1, sizeof(header.iBitsPerPixel), poOpenInfo->fp ); if( header.iBitsPerPixel != 8 ) { CPLError( CE_Failure, CPLE_OpenFailed, "File %s has unsupported number of bits per pixel.\n", poOpenInfo->pszFilename ); return NULL; } VSIFRead( &header.iOptions, 1, sizeof(header.iOptions), poOpenInfo->fp ); if( !header.iHorBlocks || !header.iVertBlocks ) return NULL; if( header.iOptions != 0x00 && // Uncompressed header.iOptions != 0x40 && // Uncompressed header.iOptions != 0x01 && // RLE header.iOptions != 0x41 && // RLE header.iOptions != 0x0B && // LZW header.iOptions != 0x0D ) // ZLIB { CPLError( CE_Failure, CPLE_OpenFailed, "File %s. Unknown map options.\n", poOpenInfo->pszFilename ); return NULL; } } /* -------------------------------------------------------------------- */ /* Read the palette. */ /* -------------------------------------------------------------------- */ GByte palette[768]; GUInt16 i; for( i = 0; i < 256; i++ ) { VSIFRead( &palette[i * 3 + 2], 1, 1, poOpenInfo->fp ); VSIFRead( &palette[i * 3 + 1], 1, 1, poOpenInfo->fp ); VSIFRead( &palette[i * 3 + 0], 1, 1, poOpenInfo->fp ); } /* -------------------------------------------------------------------- */ /* Find block offsets. */ /* -------------------------------------------------------------------- */ GUInt32 blocks; GUInt32 *offsets; blocks = header.iHorBlocks * header.iVertBlocks; offsets = (GUInt32 *)CPLMalloc( blocks * sizeof(GUInt32) ); if( !offsets ) { CPLError( CE_Failure, CPLE_OpenFailed, "File %s. Unable to allocate offset table.\n", poOpenInfo->pszFilename ); return NULL; } if( header.iOptions == 0x00 ) { offsets[0] = VSIFTell( poOpenInfo->fp ); for( GUInt32 i = 1; i < blocks; i++ ) { offsets[i] = offsets[i - 1] + header.iBlockWidth * header.iBlockHeight; } } else { for( GUInt32 i = 0; i < blocks; i++ ) { VSIFRead( &offsets[i], 1, sizeof(offsets[i]), poOpenInfo->fp ); #ifdef CPL_MSB CPL_SWAP32PTR( &offsets[i] ); #endif if( rik3header ) { GUInt32 blockSize; VSIFRead( &blockSize, 1, sizeof(blockSize), poOpenInfo->fp ); #ifdef CPL_MSB CPL_SWAP32PTR( &blockSize ); #endif } } } /* -------------------------------------------------------------------- */ /* Final checks. */ /* -------------------------------------------------------------------- */ // File size if( VSIFEof( poOpenInfo->fp ) ) { CPLError( CE_Failure, CPLE_OpenFailed, "File %s. Read past end of file.\n", poOpenInfo->pszFilename ); return NULL; } VSIFSeek( poOpenInfo->fp, 0, SEEK_END ); GUInt32 fileSize = VSIFTell( poOpenInfo->fp ); #if RIK_HEADER_DEBUG CPLDebug( "RIK", "File size %d\n", fileSize ); #endif // Make sure the offset table is valid GUInt32 lastoffset = 0; for( GUInt32 y = 0; y < header.iVertBlocks; y++) { for( GUInt32 x = 0; x < header.iHorBlocks; x++) { if( !offsets[x + y * header.iHorBlocks] ) { continue; } if( offsets[x + y * header.iHorBlocks] >= fileSize ) { if( !y ) { CPLError( CE_Failure, CPLE_OpenFailed, "File %s too short.\n", poOpenInfo->pszFilename ); return NULL; } header.iVertBlocks = y; break; } if( offsets[x + y * header.iHorBlocks] < lastoffset ) { if( !y ) { CPLError( CE_Failure, CPLE_OpenFailed, "File %s. Corrupt offset table.\n", poOpenInfo->pszFilename ); return NULL; } header.iVertBlocks = y; break; } lastoffset = offsets[x + y * header.iHorBlocks]; } } #if RIK_HEADER_DEBUG CPLDebug( "RIK", "first offset %d\n" "last offset %d\n", offsets[0], lastoffset ); #endif const char *compression = "RLE"; if( header.iOptions == 0x00 || header.iOptions == 0x40 ) compression = "Uncompressed"; if( header.iOptions == 0x0b ) compression = "LZW"; if( header.iOptions == 0x0d ) compression = "ZLIB"; CPLDebug( "RIK", "RIK file parameters:\n" " name: %s\n" " header: %s\n" " unknown: 0x%X\n" " south: %f\n" " west: %f\n" " north: %f\n" " east: %f\n" " original scale: %d\n" " meters per pixel: %f\n" " block width: %d\n" " block height: %d\n" " horizontal blocks: %d\n" " vertical blocks: %d\n" " bits per pixel: %d\n" " options: 0x%X\n" " compression: %s\n", name, headerType, header.iUnknown, header.fSouth, header.fWest, header.fNorth, header.fEast, header.iScale, metersPerPixel, header.iBlockWidth, header.iBlockHeight, header.iHorBlocks, header.iVertBlocks, header.iBitsPerPixel, header.iOptions, compression); /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ RIKDataset *poDS; poDS = new RIKDataset(); poDS->fp = poOpenInfo->fp; poOpenInfo->fp = NULL; poDS->fTransform[0] = header.fWest - metersPerPixel / 2.0; poDS->fTransform[1] = metersPerPixel; poDS->fTransform[2] = 0.0; poDS->fTransform[3] = header.fNorth + metersPerPixel / 2.0; poDS->fTransform[4] = 0.0; poDS->fTransform[5] = -metersPerPixel; poDS->nBlockXSize = header.iBlockWidth; poDS->nBlockYSize = header.iBlockHeight; poDS->nHorBlocks = header.iHorBlocks; poDS->nVertBlocks = header.iVertBlocks; poDS->pOffsets = offsets; poDS->options = header.iOptions; poDS->nFileSize = fileSize; poDS->nRasterXSize = header.iBlockWidth * header.iHorBlocks; poDS->nRasterYSize = header.iBlockHeight * header.iVertBlocks; poDS->nBands = 1; GDALColorEntry oEntry; poDS->poColorTable = new GDALColorTable(); for( i = 0; i < 256; i++ ) { oEntry.c1 = palette[i * 3 + 2]; // Red oEntry.c2 = palette[i * 3 + 1]; // Green oEntry.c3 = palette[i * 3]; // Blue oEntry.c4 = 255; poDS->poColorTable->SetColorEntry( i, &oEntry ); } /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ poDS->SetBand( 1, new RIKRasterBand( poDS, 1 )); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Check for external overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename, poOpenInfo->papszSiblingFiles ); /* -------------------------------------------------------------------- */ /* Confirm the requested access is supported. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->eAccess == GA_Update ) { delete poDS; CPLError( CE_Failure, CPLE_NotSupported, "The RIK driver does not support update access to existing" " datasets.\n" ); return NULL; } return( poDS ); }
int ILI1Reader::ReadTable(const char *layername) { char **tokens = NULL; const char *firsttok = NULL; int ret = TRUE; int warned = FALSE; int fIndex; int geomIdx; // curLayer is NULL if we have more than one // point geometry column if(curLayer == NULL) { OGRFeature *metaFeature = NULL; metaLayer->ResetReading(); while((metaFeature = metaLayer->GetNextFeature()) != NULL ) { if(EQUAL(layername, metaFeature->GetFieldAsString(0))) { const char *geomlayername = metaFeature->GetFieldAsString(2); curLayer = GetLayerByName(geomlayername); break; } } } OGRFeatureDefn *featureDef = curLayer->GetLayerDefn(); OGRFeature *feature = NULL; // get the geometry index of the current layer // only if the model is read if(featureDef->GetFieldCount() != 0) { OGRFeature *metaFeature = NULL; metaLayer->ResetReading(); while((metaFeature = metaLayer->GetNextFeature()) != NULL ) { if(EQUAL(curLayer->GetLayerDefn()->GetName(), metaFeature->GetFieldAsString(2))) { geomIdx = metaFeature->GetFieldAsInteger(1); } } } long fpos = VSIFTell(fpItf); while (ret && (tokens = ReadParseLine())) { firsttok = CSLGetField(tokens, 0); if (EQUAL(firsttok, "OBJE")) { //Check for features spread over multiple objects if (featureDef->GetGeomType() == wkbPolygon) { //Multiple polygon rings feature = curLayer->GetFeatureRef(atol(CSLGetField(tokens, 2))); } else if (featureDef->GetGeomType() == wkbGeometryCollection) { //AREA lines spread over mutltiple objects } else { feature = NULL; } if (feature == NULL) { if (featureDef->GetFieldCount() == 0) { CPLDebug( "OGR_ILI", "No field definition found for table: %s", featureDef->GetName() ); //Model not read - use heuristics for (fIndex=1; fIndex<CSLCount(tokens); fIndex++) { char szFieldName[32]; sprintf(szFieldName, "Field%02d", fIndex); OGRFieldDefn oFieldDefn(szFieldName, OFTString); featureDef->AddFieldDefn(&oFieldDefn); } } //start new feature feature = new OGRFeature(featureDef); int fieldno = 0; for (fIndex=1; fIndex<CSLCount(tokens) && fieldno < featureDef->GetFieldCount(); fIndex++, fieldno++) { if (!EQUAL(tokens[fIndex], "@")) { //CPLDebug( "READ TABLE OGR_ILI", "Adding Field %d: %s", fieldno, tokens[fIndex]); feature->SetField(fieldno, tokens[fIndex]); if (featureDef->GetFieldDefn(fieldno)->GetType() == OFTReal && fieldno > 0 && featureDef->GetFieldDefn(fieldno-1)->GetType() == OFTReal && featureDef->GetGeomType() == wkbPoint /* // if there is no ili model read, // we have no chance to detect the // geometry column!! */ && (fieldno-2) == geomIdx) { //add Point geometry OGRPoint *ogrPoint = new OGRPoint(atof(tokens[fIndex-1]), atof(tokens[fIndex])); feature->SetGeometryDirectly(ogrPoint); } } } if (!warned && featureDef->GetFieldCount() != CSLCount(tokens)-1 && !(featureDef->GetFieldCount() == CSLCount(tokens) && EQUAL(featureDef->GetFieldDefn(featureDef->GetFieldCount()-1)->GetNameRef(), "ILI_Geometry"))) { CPLDebug( "OGR_ILI", "Field count doesn't match. %d declared, %d found", featureDef->GetFieldCount(), CSLCount(tokens)-1); warned = TRUE; } if (featureDef->GetGeomType() == wkbPolygon) feature->SetFID(atol(feature->GetFieldAsString(1))); else if (feature->GetFieldCount() > 0) feature->SetFID(atol(feature->GetFieldAsString(0))); curLayer->AddFeature(feature); } } else if (EQUAL(firsttok, "STPT")) { ReadGeom(tokens, featureDef->GetGeomType(), feature); if (EQUAL(featureDef->GetFieldDefn(featureDef->GetFieldCount()-1)->GetNameRef(), "ILI_Geometry")) { AddIliGeom(feature, featureDef->GetFieldCount()-1, fpos); //TODO: append multi-OBJECT geometries } } else if (EQUAL(firsttok, "ELIN")) { //empty geom } else if (EQUAL(firsttok, "EDGE")) { tokens = ReadParseLine(); //STPT ReadGeom(tokens, wkbMultiLineString, feature); if (EQUAL(featureDef->GetFieldDefn(featureDef->GetFieldCount()-1)->GetNameRef(), "ILI_Geometry")) { AddIliGeom(feature, featureDef->GetFieldCount()-1, fpos); } } else if (EQUAL(firsttok, "PERI")) { } else if (EQUAL(firsttok, "ETAB")) { if(HasMultiplePointGeom(layername) > 0) { OGRFeature *metaFeature = NULL; metaLayer->ResetReading(); while((metaFeature = metaLayer->GetNextFeature()) != NULL ) { int pntCln = 1; if(EQUAL(layername, metaFeature->GetFieldAsString(0)) && !EQUAL(curLayer->GetLayerDefn()->GetName(), metaFeature->GetFieldAsString(2))) { pntCln++; OGRILI1Layer *curLayerTmp = GetLayerByName(metaFeature->GetFieldAsString(2)); OGRFeature *tmpFeature = NULL; int geomIdxTmp = metaFeature->GetFieldAsInteger(1); curLayer->ResetReading(); while((tmpFeature = curLayer->GetNextFeature()) != NULL ) { OGRPoint *ogrPoint = new OGRPoint(atof(tmpFeature->GetFieldAsString(geomIdxTmp + pntCln)), atof(tmpFeature->GetFieldAsString(geomIdxTmp + pntCln + 1))); tmpFeature->SetGeometryDirectly(ogrPoint); curLayerTmp->AddFeature(tmpFeature); } } } } CSLDestroy(tokens); return TRUE; } else { CPLDebug( "OGR_ILI", "Unexpected token: %s", firsttok ); } CSLDestroy(tokens); fpos = VSIFTell(fpItf); } return ret; }
GXFHandle GXFOpen( const char * pszFilename ) { FILE *fp; GXFInfo_t *psGXF; char szTitle[71]; char **papszList; int nHeaderCount = 0; /* -------------------------------------------------------------------- */ /* We open in binary to ensure that we can efficiently seek() */ /* to any location when reading scanlines randomly. If we */ /* opened as text we might still be able to seek(), but I */ /* believe that on Windows, the C library has to read through */ /* all the data to find the right spot taking into account DOS */ /* CRs. */ /* -------------------------------------------------------------------- */ fp = VSIFOpen( pszFilename, "rb" ); if( fp == NULL ) { /* how to effectively communicate this error out? */ CPLError( CE_Failure, CPLE_OpenFailed, "Unable to open file: %s\n", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Create the GXF Information object. */ /* -------------------------------------------------------------------- */ psGXF = (GXFInfo_t *) VSICalloc( sizeof(GXFInfo_t), 1 ); psGXF->fp = fp; psGXF->dfTransformScale = 1.0; psGXF->nSense = GXFS_LL_RIGHT; psGXF->dfXPixelSize = 1.0; psGXF->dfYPixelSize = 1.0; psGXF->dfSetDummyTo = -1e12; psGXF->dfUnitToMeter = 1.0; psGXF->pszTitle = VSIStrdup(""); /* -------------------------------------------------------------------- */ /* Read the header, one line at a time. */ /* -------------------------------------------------------------------- */ while( (papszList = GXFReadHeaderValue( fp, szTitle)) != NULL && nHeaderCount < MAX_HEADER_COUNT ) { if( EQUALN(szTitle,"#TITL",5) ) { CPLFree( psGXF->pszTitle ); psGXF->pszTitle = CPLStrdup( papszList[0] ); } else if( EQUALN(szTitle,"#POIN",5) ) { psGXF->nRawXSize = atoi(papszList[0]); } else if( EQUALN(szTitle,"#ROWS",5) ) { psGXF->nRawYSize = atoi(papszList[0]); } else if( EQUALN(szTitle,"#PTSE",5) ) { psGXF->dfXPixelSize = CPLAtof(papszList[0]); } else if( EQUALN(szTitle,"#RWSE",5) ) { psGXF->dfYPixelSize = CPLAtof(papszList[0]); } else if( EQUALN(szTitle,"#DUMM",5) ) { memset( psGXF->szDummy, 0, sizeof(psGXF->szDummy)); strncpy( psGXF->szDummy, papszList[0], sizeof(psGXF->szDummy) - 1); psGXF->dfSetDummyTo = CPLAtof(papszList[0]); } else if( EQUALN(szTitle,"#XORI",5) ) { psGXF->dfXOrigin = CPLAtof(papszList[0]); } else if( EQUALN(szTitle,"#YORI",5) ) { psGXF->dfYOrigin = CPLAtof(papszList[0]); } else if( EQUALN(szTitle,"#ZMIN",5) ) { psGXF->dfZMinimum = CPLAtof(papszList[0]); } else if( EQUALN(szTitle,"#ZMAX",5) ) { psGXF->dfZMaximum = CPLAtof(papszList[0]); } else if( EQUALN(szTitle,"#SENS",5) ) { psGXF->nSense = atoi(papszList[0]); } else if( EQUALN(szTitle,"#MAP_PROJECTION",8) ) { psGXF->papszMapProjection = papszList; papszList = NULL; } else if( EQUALN(szTitle,"#MAP_D",5) ) { psGXF->papszMapDatumTransform = papszList; papszList = NULL; } else if( EQUALN(szTitle,"#UNIT",5) ) { char **papszFields; papszFields = CSLTokenizeStringComplex( papszList[0], ", ", TRUE, TRUE ); if( CSLCount(papszFields) > 1 ) { psGXF->pszUnitName = VSIStrdup( papszFields[0] ); psGXF->dfUnitToMeter = CPLAtof( papszFields[1] ); if( psGXF->dfUnitToMeter == 0.0 ) psGXF->dfUnitToMeter = 1.0; } CSLDestroy( papszFields ); } else if( EQUALN(szTitle,"#TRAN",5) ) { char **papszFields; papszFields = CSLTokenizeStringComplex( papszList[0], ", ", TRUE, TRUE ); if( CSLCount(papszFields) > 1 ) { psGXF->dfTransformScale = CPLAtof(papszFields[0]); psGXF->dfTransformOffset = CPLAtof(papszFields[1]); } if( CSLCount(papszFields) > 2 ) psGXF->pszTransformName = CPLStrdup( papszFields[2] ); CSLDestroy( papszFields ); } else if( EQUALN(szTitle,"#GTYPE",5) ) { psGXF->nGType = atoi(papszList[0]); } CSLDestroy( papszList ); nHeaderCount ++; } CSLDestroy( papszList ); /* -------------------------------------------------------------------- */ /* Did we find the #GRID? */ /* -------------------------------------------------------------------- */ if( !EQUALN(szTitle,"#GRID",5) ) { GXFClose( psGXF ); CPLError( CE_Failure, CPLE_WrongFormat, "Didn't parse through to #GRID successfully in.\n" "file `%s'.\n", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Allocate, and initialize the raw scanline offset array. */ /* -------------------------------------------------------------------- */ if( psGXF->nRawYSize <= 0 ) { GXFClose( psGXF ); return NULL; } psGXF->panRawLineOffset = (long *) VSICalloc( sizeof(long), psGXF->nRawYSize+1 ); if( psGXF->panRawLineOffset == NULL ) { GXFClose( psGXF ); return NULL; } psGXF->panRawLineOffset[0] = VSIFTell( psGXF->fp ); /* -------------------------------------------------------------------- */ /* Update the zmin/zmax values to take into account #TRANSFORM */ /* information. */ /* -------------------------------------------------------------------- */ if( psGXF->dfZMinimum != 0.0 || psGXF->dfZMaximum != 0.0 ) { psGXF->dfZMinimum = (psGXF->dfZMinimum * psGXF->dfTransformScale) + psGXF->dfTransformOffset; psGXF->dfZMaximum = (psGXF->dfZMaximum * psGXF->dfTransformScale) + psGXF->dfTransformOffset; } return( (GXFHandle) psGXF ); }
static int GXFReadRawScanlineFrom( GXFInfo_t * psGXF, long iOffset, long * pnNewOffset, double * padfLineBuf ) { const char *pszLine; int nValuesRead = 0, nValuesSought = psGXF->nRawXSize; VSIFSeek( psGXF->fp, iOffset, SEEK_SET ); while( nValuesRead < nValuesSought ) { pszLine = CPLReadLine( psGXF->fp ); if( pszLine == NULL ) break; /* -------------------------------------------------------------------- */ /* Uncompressed case. */ /* -------------------------------------------------------------------- */ if( psGXF->nGType == 0 ) { /* we could just tokenize the line, but that's pretty expensive. Instead I will parse on white space ``by hand''. */ while( *pszLine != '\0' && nValuesRead < nValuesSought ) { int i; /* skip leading white space */ for( ; isspace((unsigned char)*pszLine); pszLine++ ) {} /* Skip the data value (non white space) */ for( i = 0; pszLine[i] != '\0' && !isspace((unsigned char)pszLine[i]); i++) {} if( strncmp(pszLine,psGXF->szDummy,i) == 0 ) { padfLineBuf[nValuesRead++] = psGXF->dfSetDummyTo; } else { padfLineBuf[nValuesRead++] = CPLAtof(pszLine); } /* skip further whitespace */ for( pszLine += i; isspace((unsigned char)*pszLine); pszLine++ ) {} } } /* -------------------------------------------------------------------- */ /* Compressed case. */ /* -------------------------------------------------------------------- */ else { int nLineLen = (int)strlen(pszLine); while( *pszLine != '\0' && nValuesRead < nValuesSought ) { if( nLineLen < psGXF->nGType ) return CE_Failure; if( pszLine[0] == '!' ) { padfLineBuf[nValuesRead++] = psGXF->dfSetDummyTo; } else if( pszLine[0] == '"' ) { int nCount, i; double dfValue; pszLine += psGXF->nGType; nLineLen -= psGXF->nGType; if( nLineLen < psGXF->nGType ) { pszLine = CPLReadLine( psGXF->fp ); if( pszLine == NULL ) return CE_Failure; nLineLen = (int)strlen(pszLine); if( nLineLen < psGXF->nGType ) return CE_Failure; } nCount = (int) GXFParseBase90( psGXF, pszLine, FALSE); pszLine += psGXF->nGType; nLineLen -= psGXF->nGType; if( nLineLen < psGXF->nGType ) { pszLine = CPLReadLine( psGXF->fp ); if( pszLine == NULL ) return CE_Failure; nLineLen = (int)strlen(pszLine); if( nLineLen < psGXF->nGType ) return CE_Failure; } if( *pszLine == '!' ) dfValue = psGXF->dfSetDummyTo; else dfValue = GXFParseBase90( psGXF, pszLine, TRUE ); if( nValuesRead + nCount > nValuesSought ) { CPLError(CE_Failure, CPLE_AppDefined, "Wrong count value"); return CE_Failure; } for( i=0; i < nCount && nValuesRead < nValuesSought; i++ ) padfLineBuf[nValuesRead++] = dfValue; } else { padfLineBuf[nValuesRead++] = GXFParseBase90( psGXF, pszLine, TRUE ); } pszLine += psGXF->nGType; nLineLen -= psGXF->nGType; } } } /* -------------------------------------------------------------------- */ /* Return the new offset, if requested. */ /* -------------------------------------------------------------------- */ if( pnNewOffset != NULL ) { *pnNewOffset = VSIFTell( psGXF->fp ); } return CE_None; }
GDALDataset *IDADataset::Open( GDALOpenInfo * poOpenInfo ) { /* -------------------------------------------------------------------- */ /* Is this an IDA file? */ /* -------------------------------------------------------------------- */ int nXSize, nYSize; GIntBig nExpectedFileSize, nActualFileSize; if( poOpenInfo->fp == NULL ) return NULL; if( poOpenInfo->nHeaderBytes < 512 ) return NULL; // projection legal? if( poOpenInfo->pabyHeader[23] > 10 ) return NULL; // imagetype legal? if( (poOpenInfo->pabyHeader[22] > 14 && poOpenInfo->pabyHeader[22] < 100) || (poOpenInfo->pabyHeader[22] > 114 && poOpenInfo->pabyHeader[22] != 200 ) ) return NULL; nXSize = poOpenInfo->pabyHeader[30] + poOpenInfo->pabyHeader[31] * 256; nYSize = poOpenInfo->pabyHeader[32] + poOpenInfo->pabyHeader[33] * 256; if( nXSize == 0 || nYSize == 0 ) return NULL; // The file just be exactly the image size + header size in length. nExpectedFileSize = nXSize * nYSize + 512; VSIFSeek( poOpenInfo->fp, 0, SEEK_END ); nActualFileSize = VSIFTell( poOpenInfo->fp ); VSIRewind( poOpenInfo->fp ); if( nActualFileSize != nExpectedFileSize ) return NULL; /* -------------------------------------------------------------------- */ /* Create the dataset. */ /* -------------------------------------------------------------------- */ IDADataset *poDS = new IDADataset(); memcpy( poDS->abyHeader, poOpenInfo->pabyHeader, 512 ); /* -------------------------------------------------------------------- */ /* Parse various values out of the header. */ /* -------------------------------------------------------------------- */ poDS->nImageType = poOpenInfo->pabyHeader[22]; poDS->nProjection = poOpenInfo->pabyHeader[23]; poDS->nRasterYSize = poOpenInfo->pabyHeader[30] + poOpenInfo->pabyHeader[31] * 256; poDS->nRasterXSize = poOpenInfo->pabyHeader[32] + poOpenInfo->pabyHeader[33] * 256; strncpy( poDS->szTitle, (const char *) poOpenInfo->pabyHeader+38, 80 ); poDS->szTitle[80] = '\0'; int nLastTitleChar = strlen(poDS->szTitle)-1; while( nLastTitleChar > -1 && (poDS->szTitle[nLastTitleChar] == 10 || poDS->szTitle[nLastTitleChar] == 13 || poDS->szTitle[nLastTitleChar] == ' ') ) poDS->szTitle[nLastTitleChar--] = '\0'; poDS->dfLatCenter = tp2c( poOpenInfo->pabyHeader + 120 ); poDS->dfLongCenter = tp2c( poOpenInfo->pabyHeader + 126 ); poDS->dfXCenter = tp2c( poOpenInfo->pabyHeader + 132 ); poDS->dfYCenter = tp2c( poOpenInfo->pabyHeader + 138 ); poDS->dfDX = tp2c( poOpenInfo->pabyHeader + 144 ); poDS->dfDY = tp2c( poOpenInfo->pabyHeader + 150 ); poDS->dfParallel1 = tp2c( poOpenInfo->pabyHeader + 156 ); poDS->dfParallel2 = tp2c( poOpenInfo->pabyHeader + 162 ); poDS->ProcessGeoref(); poDS->SetMetadataItem( "TITLE", poDS->szTitle ); /* -------------------------------------------------------------------- */ /* Handle various image types. */ /* -------------------------------------------------------------------- */ /* GENERIC = 0 FEW S NDVI = 1 EROS NDVI = 6 ARTEMIS CUTOFF = 10 ARTEMIS RECODE = 11 ARTEMIS NDVI = 12 ARTEMIS FEWS = 13 ARTEMIS NEWNASA = 14 GENERIC DIFF = 100 FEW S NDVI DIFF = 101 EROS NDVI DIFF = 106 ARTEMIS CUTOFF DIFF = 110 ARTEMIS RECODE DIFF = 111 ARTEMIS NDVI DIFF = 112 ARTEMIS FEWS DIFF = 113 ARTEMIS NEWNASA DIFF = 114 CALCULATED =200 */ poDS->nMissing = 0; switch( poDS->nImageType ) { case 1: poDS->SetMetadataItem( "IMAGETYPE", "1, FEWS NDVI" ); poDS->dfM = 1/256.0; poDS->dfB = -82/256.0; break; case 6: poDS->SetMetadataItem( "IMAGETYPE", "6, EROS NDVI" ); poDS->dfM = 1/100.0; poDS->dfB = -100/100.0; break; case 10: poDS->SetMetadataItem( "IMAGETYPE", "10, ARTEMIS CUTOFF" ); poDS->dfM = 1.0; poDS->dfB = 0.0; poDS->nMissing = 254; break; case 11: poDS->SetMetadataItem( "IMAGETYPE", "11, ARTEMIS RECODE" ); poDS->dfM = 4.0; poDS->dfB = 0.0; poDS->nMissing = 254; break; case 12: /* ANDVI */ poDS->SetMetadataItem( "IMAGETYPE", "12, ARTEMIS NDVI" ); poDS->dfM = 4/500.0; poDS->dfB = -3/500.0 - 1.0; poDS->nMissing = 254; break; case 13: /* AFEWS */ poDS->SetMetadataItem( "IMAGETYPE", "13, ARTEMIS FEWS" ); poDS->dfM = 1/256.0; poDS->dfB = -82/256.0; poDS->nMissing = 254; break; case 14: /* NEWNASA */ poDS->SetMetadataItem( "IMAGETYPE", "13, ARTEMIS NEWNASA" ); poDS->dfM = 0.75/250.0; poDS->dfB = 0.0; poDS->nMissing = 254; break; case 101: /* NDVI_DIFF (FEW S) */ poDS->dfM = 1/128.0; poDS->dfB = -1.0; poDS->nMissing = 0; break; case 106: /* EROS_DIFF */ poDS->dfM = 1/50.0; poDS->dfB = -128/50.0; poDS->nMissing = 0; break; case 110: /* CUTOFF_DIFF */ poDS->dfM = 2.0; poDS->dfB = -128*2; poDS->nMissing = 254; break; case 111: /* RECODE_DIFF */ poDS->dfM = 8; poDS->dfB = -128*8; poDS->nMissing = 254; break; case 112: /* ANDVI_DIFF */ poDS->dfM = 8/1000.0; poDS->dfB = (-128*8)/1000.0; poDS->nMissing = 254; break; case 113: /* AFEWS_DIFF */ poDS->dfM = 1/128.0; poDS->dfB = -1; poDS->nMissing = 254; break; case 114: /* NEWNASA_DIFF */ poDS->dfM = 0.75/125.0; poDS->dfB = -128*poDS->dfM; poDS->nMissing = 254; break; case 200: /* we use the values from the header */ poDS->dfM = tp2c( poOpenInfo->pabyHeader + 171 ); poDS->dfB = tp2c( poOpenInfo->pabyHeader + 177 ); poDS->nMissing = poOpenInfo->pabyHeader[170]; break; default: poDS->dfM = 1.0; poDS->dfB = 0.0; break; } /* -------------------------------------------------------------------- */ /* Create the band. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->eAccess == GA_ReadOnly ) { poDS->fpRaw = poOpenInfo->fp; poOpenInfo->fp = NULL; } else { poDS->fpRaw = VSIFOpen( poOpenInfo->pszFilename, "rb+" ); poDS->eAccess = GA_Update; if( poDS->fpRaw == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open %s for write access.", poOpenInfo->pszFilename ); return NULL; } } poDS->SetBand( 1, new IDARasterBand( poDS, poDS->fpRaw, poDS->nRasterXSize ) ); /* -------------------------------------------------------------------- */ /* Check for a color table. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->ReadColorTable(); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Check for overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename ); return( poDS ); }
OGRRECLayer::OGRRECLayer( const char *pszLayerNameIn, FILE * fp, int nFieldCountIn ) { fpREC = fp; bIsValid = FALSE; nStartOfData = 0; nNextFID = 1; poFeatureDefn = new OGRFeatureDefn( pszLayerNameIn ); SetDescription( poFeatureDefn->GetName() ); poFeatureDefn->Reference(); nFieldCount = 0; panFieldOffset = (int *) CPLCalloc(sizeof(int),nFieldCountIn); panFieldWidth = (int *) CPLCalloc(sizeof(int),nFieldCountIn); /* -------------------------------------------------------------------- */ /* Read field definition lines. */ /* -------------------------------------------------------------------- */ int iField; for( nFieldCount=0, iField = 0; iField < nFieldCountIn; iField++ ) { const char *pszLine = CPLReadLine( fp ); int nTypeCode; OGRFieldType eFType = OFTString; if( pszLine == NULL ) return; if( strlen(pszLine) < 44 ) return; // Extract field width. panFieldWidth[nFieldCount] = atoi( RECGetField( pszLine, 37, 4 ) ); if( panFieldWidth[nFieldCount] < 0 ) return; // Is this an real, integer or string field? Default to string. nTypeCode = atoi(RECGetField(pszLine,33,4)); if( nTypeCode == 12 ) eFType = OFTInteger; else if( nTypeCode > 100 && nTypeCode < 120 ) { eFType = OFTReal; } else if( nTypeCode == 0 || nTypeCode == 6 || nTypeCode == 102 ) { if( panFieldWidth[nFieldCount] < 3 ) eFType = OFTInteger; else eFType = OFTReal; } else eFType = OFTString; OGRFieldDefn oField( RECGetField( pszLine, 2, 10 ), eFType ); // Establish field offset. if( nFieldCount > 0 ) panFieldOffset[nFieldCount] = panFieldOffset[nFieldCount-1] + panFieldWidth[nFieldCount-1]; if( nTypeCode > 100 && nTypeCode < 120 ) { oField.SetWidth( panFieldWidth[nFieldCount] ); oField.SetPrecision( nTypeCode - 100 ); } else if( eFType == OFTReal ) { oField.SetWidth( panFieldWidth[nFieldCount]*2 ); oField.SetPrecision( panFieldWidth[nFieldCount]-1 ); } else oField.SetWidth( panFieldWidth[nFieldCount] ); // Skip fields that are only screen labels. if( panFieldWidth[nFieldCount] == 0 ) continue; poFeatureDefn->AddFieldDefn( &oField ); nFieldCount++; } if( nFieldCount == 0 ) return; nRecordLength = panFieldOffset[nFieldCount-1]+panFieldWidth[nFieldCount-1]; bIsValid = TRUE; nStartOfData = VSIFTell( fp ); }
void OGRGMLDataSource::InsertHeader() { FILE *fpSchema; int nSchemaStart = 0; if( fpOutput == NULL || fpOutput == stdout ) return; /* -------------------------------------------------------------------- */ /* Do we want to write the schema within the GML instance doc */ /* or to a separate file? For now we only support external. */ /* -------------------------------------------------------------------- */ const char *pszSchemaURI = CSLFetchNameValue(papszCreateOptions, "XSISCHEMAURI"); const char *pszSchemaOpt = CSLFetchNameValue( papszCreateOptions, "XSISCHEMA" ); if( pszSchemaURI != NULL ) return; if( pszSchemaOpt == NULL || EQUAL(pszSchemaOpt,"EXTERNAL") ) { const char *pszXSDFilename = CPLResetExtension( pszName, "xsd" ); fpSchema = VSIFOpen( pszXSDFilename, "wt" ); if( fpSchema == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open file %.500s for schema output.", pszXSDFilename ); return; } fprintf( fpSchema, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ); } else if( EQUAL(pszSchemaOpt,"INTERNAL") ) { nSchemaStart = VSIFTell( fpOutput ); fpSchema = fpOutput; } else return; /* ==================================================================== */ /* Write the schema section at the end of the file. Once */ /* complete, we will read it back in, and then move the whole */ /* file "down" enough to insert the schema at the beginning. */ /* ==================================================================== */ /* -------------------------------------------------------------------- */ /* Emit the start of the schema section. */ /* -------------------------------------------------------------------- */ const char *pszTargetNameSpace = "http://ogr.maptools.org/"; const char *pszPrefix = "ogr"; VSIFPrintf( fpSchema, "<xs:schema targetNamespace=\"%s\" xmlns:%s=\"%s\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:gml=\"http://www.opengis.net/gml\" elementFormDefault=\"qualified\" version=\"1.0\">\n", pszTargetNameSpace, pszPrefix, pszTargetNameSpace ); VSIFPrintf( fpSchema, "<xs:import namespace=\"http://www.opengis.net/gml\" schemaLocation=\"http://schemas.opengeospatial.net/gml/2.1.2/feature.xsd\"/>" ); /* -------------------------------------------------------------------- */ /* Define the FeatureCollection */ /* -------------------------------------------------------------------- */ VSIFPrintf( fpSchema, "<xs:element name=\"FeatureCollection\" type=\"%s:FeatureCollectionType\" substitutionGroup=\"gml:_FeatureCollection\"/>\n", pszPrefix ); VSIFPrintf( fpSchema, "<xs:complexType name=\"FeatureCollectionType\">\n" " <xs:complexContent>\n" " <xs:extension base=\"gml:AbstractFeatureCollectionType\">\n" " <xs:attribute name=\"lockId\" type=\"xs:string\" use=\"optional\"/>\n" " <xs:attribute name=\"scope\" type=\"xs:string\" use=\"optional\"/>\n" " </xs:extension>\n" " </xs:complexContent>\n" "</xs:complexType>\n" ); /* ==================================================================== */ /* Define the schema for each layer. */ /* ==================================================================== */ int iLayer; for( iLayer = 0; iLayer < GetLayerCount(); iLayer++ ) { OGRFeatureDefn *poFDefn = GetLayer(iLayer)->GetLayerDefn(); /* -------------------------------------------------------------------- */ /* Emit initial stuff for a feature type. */ /* -------------------------------------------------------------------- */ VSIFPrintf( fpSchema, "<xs:element name=\"%s\" type=\"%s:%s_Type\" substitutionGroup=\"gml:_Feature\"/>\n", poFDefn->GetName(), pszPrefix, poFDefn->GetName() ); VSIFPrintf( fpSchema, "<xs:complexType name=\"%s_Type\">\n" " <xs:complexContent>\n" " <xs:extension base=\"gml:AbstractFeatureType\">\n" " <xs:sequence>\n", poFDefn->GetName() ); /* -------------------------------------------------------------------- */ /* Define the geometry attribute. For now I always use the */ /* generic geometry type, but eventually we should express */ /* particulars if available. */ /* -------------------------------------------------------------------- */ VSIFPrintf( fpSchema, "<xs:element name=\"geometryProperty\" type=\"gml:GeometryPropertyType\" nillable=\"true\" minOccurs=\"1\" maxOccurs=\"1\"/>\n" ); /* -------------------------------------------------------------------- */ /* Emit each of the attributes. */ /* -------------------------------------------------------------------- */ for( int iField = 0; iField < poFDefn->GetFieldCount(); iField++ ) { OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField); if( poFieldDefn->GetType() == OFTInteger ) { int nWidth; if( poFieldDefn->GetWidth() > 0 ) nWidth = poFieldDefn->GetWidth(); else nWidth = 16; VSIFPrintf( fpSchema, " <xs:element name=\"%s\" nillable=\"true\" minOccurs=\"0\" maxOccurs=\"1\">\n" " <xs:simpleType>\n" " <xs:restriction base=\"xs:integer\">\n" " <xs:totalDigits value=\"%d\"/>\n" " </xs:restriction>\n" " </xs:simpleType>\n" " </xs:element>\n", poFieldDefn->GetNameRef(), nWidth ); } else if( poFieldDefn->GetType() == OFTReal ) { int nWidth, nDecimals; if( poFieldDefn->GetPrecision() == 0 ) nDecimals = 0; else nDecimals = poFieldDefn->GetPrecision(); if( poFieldDefn->GetWidth() > 0 ) nWidth = poFieldDefn->GetWidth(); else nWidth = 33; VSIFPrintf( fpSchema, " <xs:element name=\"%s\" nillable=\"true\" minOccurs=\"0\" maxOccurs=\"1\">\n" " <xs:simpleType>\n" " <xs:restriction base=\"xs:decimal\">\n" " <xs:totalDigits value=\"%d\"/>\n" " <xs:fractionDigits value=\"%d\"/>\n" " </xs:restriction>\n" " </xs:simpleType>\n" " </xs:element>\n", poFieldDefn->GetNameRef(), nWidth, nDecimals ); } else if( poFieldDefn->GetType() == OFTString ) { char szMaxLength[48]; if( poFieldDefn->GetWidth() == 0 ) sprintf( szMaxLength, "unbounded" ); else sprintf( szMaxLength, "%d", poFieldDefn->GetWidth() ); VSIFPrintf( fpSchema, " <xs:element name=\"%s\" nillable=\"true\" minOccurs=\"0\" maxOccurs=\"1\">\n" " <xs:simpleType>\n" " <xs:restriction base=\"xs:string\">\n" " <xs:maxLength value=\"%s\"/>\n" " </xs:restriction>\n" " </xs:simpleType>\n" " </xs:element>\n", poFieldDefn->GetNameRef(), szMaxLength ); } else if( poFieldDefn->GetType() == OFTDate || poFieldDefn->GetType() == OFTDateTime ) { VSIFPrintf( fpSchema, " <xs:element name=\"%s\" nillable=\"true\" minOccurs=\"0\" maxOccurs=\"1\">\n" " <xs:simpleType>\n" " <xs:restriction base=\"xs:string\">\n" " <xs:maxLength value=\"unbounded\"/>\n" " </xs:restriction>\n" " </xs:simpleType>\n" " </xs:element>\n", poFieldDefn->GetNameRef() ); } else { /* TODO */ } } /* next field */ /* -------------------------------------------------------------------- */ /* Finish off feature type. */ /* -------------------------------------------------------------------- */ VSIFPrintf( fpSchema, " </xs:sequence>\n" " </xs:extension>\n" " </xs:complexContent>\n" "</xs:complexType>\n" ); } /* next layer */ VSIFPrintf( fpSchema, "</xs:schema>\n" ); /* ==================================================================== */ /* Move schema to the start of the file. */ /* ==================================================================== */ if( fpSchema == fpOutput ) { /* -------------------------------------------------------------------- */ /* Read the schema into memory. */ /* -------------------------------------------------------------------- */ int nSchemaSize = VSIFTell( fpOutput ) - nSchemaStart; char *pszSchema = (char *) CPLMalloc(nSchemaSize+1); VSIFSeek( fpOutput, nSchemaStart, SEEK_SET ); VSIFRead( pszSchema, 1, nSchemaSize, fpOutput ); pszSchema[nSchemaSize] = '\0'; /* -------------------------------------------------------------------- */ /* Move file data down by "schema size" bytes from after <?xml> */ /* header so we have room insert the schema. Move in pretty */ /* big chunks. */ /* -------------------------------------------------------------------- */ int nChunkSize = MIN(nSchemaStart-nSchemaInsertLocation,250000); char *pszChunk = (char *) CPLMalloc(nChunkSize); int nEndOfUnmovedData = nSchemaStart; for( nEndOfUnmovedData = nSchemaStart; nEndOfUnmovedData > nSchemaInsertLocation; ) { int nBytesToMove = MIN(nChunkSize, nEndOfUnmovedData - nSchemaInsertLocation ); VSIFSeek( fpOutput, nEndOfUnmovedData - nBytesToMove, SEEK_SET ); VSIFRead( pszChunk, 1, nBytesToMove, fpOutput ); VSIFSeek( fpOutput, nEndOfUnmovedData - nBytesToMove + nSchemaSize, SEEK_SET ); VSIFWrite( pszChunk, 1, nBytesToMove, fpOutput ); nEndOfUnmovedData -= nBytesToMove; } CPLFree( pszChunk ); /* -------------------------------------------------------------------- */ /* Write the schema in the opened slot. */ /* -------------------------------------------------------------------- */ VSIFSeek( fpOutput, nSchemaInsertLocation, SEEK_SET ); VSIFWrite( pszSchema, 1, nSchemaSize, fpOutput ); VSIFSeek( fpOutput, 0, SEEK_END ); nBoundedByLocation += nSchemaSize; } /* -------------------------------------------------------------------- */ /* Close external schema files. */ /* -------------------------------------------------------------------- */ else VSIFClose( fpSchema ); }
/********************************************************************** * TABRawBinBlock::CommitToFile() * * Commit the current state of the binary block to the file to which * it has been previously attached. * * Derived classes may want to (optionally) reimplement this method if * they need to do special processing before committing the block to disk. * * For files created with bHardBlockSize=TRUE, a complete block of * the specified size is always written, otherwise only the number of * used bytes in the block will be written to disk. * * Returns 0 if succesful or -1 if an error happened, in which case * CPLError() will have been called. **********************************************************************/ int TABRawBinBlock::CommitToFile() { int nStatus = 0; if (m_fp == NULL || m_nBlockSize <= 0 || m_pabyBuf == NULL || m_nFileOffset < 0) { CPLError(CE_Failure, CPLE_AssertionFailed, "TABRawBinBlock::CommitToFile(): Block has not been initialized yet!"); return -1; } /*---------------------------------------------------------------- * If block has not been modified, then just return... nothing to do. *---------------------------------------------------------------*/ if (!m_bModified) return 0; /*---------------------------------------------------------------- * Move the output file pointer to the right position... *---------------------------------------------------------------*/ if (VSIFSeek(m_fp, m_nFileOffset, SEEK_SET) != 0) { /*------------------------------------------------------------ * Moving pointer failed... we may need to pad with zeros if * block destination is beyond current end of file. *-----------------------------------------------------------*/ int nCurPos; nCurPos = VSIFTell(m_fp); if (nCurPos < m_nFileOffset && VSIFSeek(m_fp, 0L, SEEK_END) == 0 && (nCurPos = VSIFTell(m_fp)) < m_nFileOffset) { GByte cZero = 0; while(nCurPos < m_nFileOffset && nStatus == 0) { if (VSIFWrite(&cZero, 1, 1, m_fp) != 1) { CPLError(CE_Failure, CPLE_FileIO, "Failed writing 1 byte at offset %d.", nCurPos); nStatus = -1; break; } nCurPos++; } } if (nCurPos != m_nFileOffset) nStatus = -1; // Error message will follow below } /*---------------------------------------------------------------- * At this point we are ready to write to the file. * * If m_bHardBlockSize==FALSE, then we do not write a complete block; * we write only the part of the block that was used. *---------------------------------------------------------------*/ int numBytesToWrite = m_bHardBlockSize?m_nBlockSize:m_nSizeUsed; if (nStatus != 0 || VSIFWrite(m_pabyBuf,sizeof(GByte), numBytesToWrite, m_fp) != (size_t)numBytesToWrite ) { CPLError(CE_Failure, CPLE_FileIO, "Failed writing %d bytes at offset %d.", numBytesToWrite, m_nFileOffset); return -1; } fflush(m_fp); m_bModified = FALSE; return 0; }
OGRErr OGRMILayerAttrIndex::LoadConfigFromXML() { FILE *fp; int nXMLSize; char *pszRawXML; CPLAssert( poINDFile == NULL ); /* -------------------------------------------------------------------- */ /* Read the XML file. */ /* -------------------------------------------------------------------- */ fp = VSIFOpen( pszMetadataFilename, "rb" ); if( fp == NULL ) return OGRERR_NONE; VSIFSeek( fp, 0, SEEK_END ); nXMLSize = VSIFTell( fp ); VSIFSeek( fp, 0, SEEK_SET ); pszRawXML = (char *) CPLMalloc(nXMLSize+1); pszRawXML[nXMLSize] = '\0'; VSIFRead( pszRawXML, nXMLSize, 1, fp ); VSIFClose( fp ); /* -------------------------------------------------------------------- */ /* Parse the XML. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psRoot = CPLParseXMLString( pszRawXML ); CPLFree( pszRawXML ); if( psRoot == NULL ) return OGRERR_FAILURE; /* -------------------------------------------------------------------- */ /* Open the index file. */ /* -------------------------------------------------------------------- */ poINDFile = new TABINDFile(); if( poINDFile->Open( pszMetadataFilename, "r+" ) != 0 ) { CPLDestroyXMLNode( psRoot ); CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open index file %s.", pszMIINDFilename ); return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Process each attrindex. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psAttrIndex; for( psAttrIndex = psRoot->psChild; psAttrIndex != NULL; psAttrIndex = psAttrIndex->psNext ) { int iField, iIndexIndex; if( psAttrIndex->eType != CXT_Element || !EQUAL(psAttrIndex->pszValue,"OGRMIAttrIndex") ) continue; iField = atoi(CPLGetXMLValue(psAttrIndex,"FieldIndex","-1")); iIndexIndex = atoi(CPLGetXMLValue(psAttrIndex,"IndexIndex","-1")); if( iField == -1 || iIndexIndex == -1 ) { CPLError( CE_Warning, CPLE_AppDefined, "Skipping corrupt OGRMIAttrIndex entry." ); continue; } AddAttrInd( iField, iIndexIndex ); } CPLDestroyXMLNode( psRoot ); CPLDebug( "OGR", "Restored %d field indexes for layer %s from %s on %s.", nIndexCount, poLayer->GetLayerDefn()->GetName(), pszMetadataFilename, pszMIINDFilename ); return OGRERR_NONE; }
vsi_l_offset VSIFTellL( FILE * fp ) { return static_cast<vsi_l_offset>(VSIFTell(fp)); }
int DDFModule::Open( const char * pszFilename, int bFailQuietly ) { static const size_t nLeaderSize = 24; /* -------------------------------------------------------------------- */ /* Close the existing file if there is one. */ /* -------------------------------------------------------------------- */ if( fpDDF != NULL ) Close(); /* -------------------------------------------------------------------- */ /* Open the file. */ /* -------------------------------------------------------------------- */ fpDDF = VSIFOpen( pszFilename, "rb" ); if( fpDDF == NULL ) { if( !bFailQuietly ) CPLError( CE_Failure, CPLE_OpenFailed, "Unable to open DDF file `%s'.", pszFilename ); return FALSE; } /* -------------------------------------------------------------------- */ /* Read the 24 byte leader. */ /* -------------------------------------------------------------------- */ char achLeader[nLeaderSize]; if( VSIFRead( achLeader, 1, nLeaderSize, fpDDF ) != nLeaderSize ) { VSIFClose( fpDDF ); fpDDF = NULL; if( !bFailQuietly ) CPLError( CE_Failure, CPLE_FileIO, "Leader is short on DDF file `%s'.", pszFilename ); return FALSE; } /* -------------------------------------------------------------------- */ /* Verify that this appears to be a valid DDF file. */ /* -------------------------------------------------------------------- */ int i, bValid = TRUE; for( i = 0; i < (int)nLeaderSize; i++ ) { if( achLeader[i] < 32 || achLeader[i] > 126 ) bValid = FALSE; } if( achLeader[5] != '1' && achLeader[5] != '2' && achLeader[5] != '3' ) bValid = FALSE; if( achLeader[6] != 'L' ) bValid = FALSE; if( achLeader[8] != '1' && achLeader[8] != ' ' ) bValid = FALSE; /* -------------------------------------------------------------------- */ /* Extract information from leader. */ /* -------------------------------------------------------------------- */ if( bValid ) { _recLength = DDFScanInt( achLeader+0, 5 ); _interchangeLevel = achLeader[5]; _leaderIden = achLeader[6]; _inlineCodeExtensionIndicator = achLeader[7]; _versionNumber = achLeader[8]; _appIndicator = achLeader[9]; _fieldControlLength = DDFScanInt(achLeader+10,2); _fieldAreaStart = DDFScanInt(achLeader+12,5); _extendedCharSet[0] = achLeader[17]; _extendedCharSet[1] = achLeader[18]; _extendedCharSet[2] = achLeader[19]; _extendedCharSet[3] = '\0'; _sizeFieldLength = DDFScanInt(achLeader+20,1); _sizeFieldPos = DDFScanInt(achLeader+21,1); _sizeFieldTag = DDFScanInt(achLeader+23,1); if( _recLength < 12 || _fieldControlLength == 0 || _fieldAreaStart < 24 || _sizeFieldLength == 0 || _sizeFieldPos == 0 || _sizeFieldTag == 0 ) { bValid = FALSE; } } /* -------------------------------------------------------------------- */ /* If the header is invalid, then clean up, report the error */ /* and return. */ /* -------------------------------------------------------------------- */ if( !bValid ) { VSIFClose( fpDDF ); fpDDF = NULL; if( !bFailQuietly ) CPLError( CE_Failure, CPLE_AppDefined, "File `%s' does not appear to have\n" "a valid ISO 8211 header.\n", pszFilename ); return FALSE; } /* -------------------------------------------------------------------- */ /* Read the whole record info memory. */ /* -------------------------------------------------------------------- */ char *pachRecord; pachRecord = (char *) CPLMalloc(_recLength); memcpy( pachRecord, achLeader, nLeaderSize ); if( VSIFRead( pachRecord+nLeaderSize, 1, _recLength-nLeaderSize, fpDDF ) != _recLength - nLeaderSize ) { if( !bFailQuietly ) CPLError( CE_Failure, CPLE_FileIO, "Header record is short on DDF file `%s'.", pszFilename ); return FALSE; } /* -------------------------------------------------------------------- */ /* First make a pass counting the directory entries. */ /* -------------------------------------------------------------------- */ int nFieldEntryWidth, nFDCount = 0; nFieldEntryWidth = _sizeFieldLength + _sizeFieldPos + _sizeFieldTag; for( i = nLeaderSize; i < _recLength; i += nFieldEntryWidth ) { if( pachRecord[i] == DDF_FIELD_TERMINATOR ) break; nFDCount++; } /* -------------------------------------------------------------------- */ /* Allocate, and read field definitions. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nFDCount; i++ ) { char szTag[128]; int nEntryOffset = nLeaderSize + i*nFieldEntryWidth; int nFieldLength, nFieldPos; DDFFieldDefn *poFDefn; strncpy( szTag, pachRecord+nEntryOffset, _sizeFieldTag ); szTag[_sizeFieldTag] = '\0'; nEntryOffset += _sizeFieldTag; nFieldLength = DDFScanInt( pachRecord+nEntryOffset, _sizeFieldLength ); nEntryOffset += _sizeFieldLength; nFieldPos = DDFScanInt( pachRecord+nEntryOffset, _sizeFieldPos ); poFDefn = new DDFFieldDefn(); if( poFDefn->Initialize( this, szTag, nFieldLength, pachRecord+_fieldAreaStart+nFieldPos ) ) AddField( poFDefn ); else delete poFDefn; } CPLFree( pachRecord ); /* -------------------------------------------------------------------- */ /* Record the current file offset, the beginning of the first */ /* data record. */ /* -------------------------------------------------------------------- */ nFirstRecordOffset = VSIFTell( fpDDF ); return TRUE; }
GDALDataset *XPMDataset::Open( GDALOpenInfo * poOpenInfo ) { /* -------------------------------------------------------------------- */ /* First we check to see if the file has the expected header */ /* bytes. For now we expect the XPM file to start with a line */ /* containing the letters XPM, and to have "static" in the */ /* header. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->nHeaderBytes < 32 || strstr((const char *) poOpenInfo->pabyHeader,"XPM") == NULL || strstr((const char *) poOpenInfo->pabyHeader,"static") == NULL ) return NULL; if( poOpenInfo->eAccess == GA_Update ) { CPLError( CE_Failure, CPLE_NotSupported, "The XPM driver does not support update access to existing" " files." ); return NULL; } if (poOpenInfo->fp == NULL) return NULL; /* -------------------------------------------------------------------- */ /* Read the whole file into a memory strings. */ /* -------------------------------------------------------------------- */ unsigned int nFileSize; char *pszFileContents; VSIFSeek( poOpenInfo->fp, 0, SEEK_END ); nFileSize = VSIFTell( poOpenInfo->fp ); pszFileContents = (char *) VSIMalloc(nFileSize+1); if( pszFileContents == NULL ) { CPLError( CE_Failure, CPLE_OutOfMemory, "Insufficient memory for loading XPM file %s into memory.", poOpenInfo->pszFilename ); return NULL; } pszFileContents[nFileSize] = '\0'; VSIFSeek( poOpenInfo->fp, 0, SEEK_SET ); if( VSIFRead( pszFileContents, 1, nFileSize, poOpenInfo->fp ) != nFileSize) { CPLFree( pszFileContents ); CPLError( CE_Failure, CPLE_FileIO, "Failed to read all %d bytes from file %s.", nFileSize, poOpenInfo->pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Convert into a binary image. */ /* -------------------------------------------------------------------- */ GByte *pabyImage; int nXSize, nYSize; GDALColorTable *poCT = NULL; CPLErrorReset(); pabyImage = ParseXPM( pszFileContents, &nXSize, &nYSize, &poCT ); CPLFree( pszFileContents ); if( pabyImage == NULL ) { return NULL; } /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ XPMDataset *poDS; poDS = new XPMDataset(); /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ poDS->nRasterXSize = nXSize; poDS->nRasterYSize = nYSize; /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ MEMRasterBand *poBand; poBand = new MEMRasterBand( poDS, 1, pabyImage, GDT_Byte, 1, nXSize, TRUE ); poBand->SetColorTable( poCT ); poDS->SetBand( 1, poBand ); delete poCT; /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Support overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename ); return poDS; }
vsi_l_offset VSIFTellL( FILE * fp ) { return (vsi_l_offset) VSIFTell( fp ); }
int OGRGMLDataSource::Create( const char *pszFilename, char **papszOptions ) { if( fpOutput != NULL || poReader != NULL ) { CPLAssert( FALSE ); return FALSE; } /* -------------------------------------------------------------------- */ /* Create the output file. */ /* -------------------------------------------------------------------- */ pszName = CPLStrdup( pszFilename ); if( EQUAL(pszFilename,"stdout") ) fpOutput = stdout; else fpOutput = VSIFOpen( pszFilename, "wt+" ); if( fpOutput == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to create GML file %s.", pszFilename ); return FALSE; } /* -------------------------------------------------------------------- */ /* Write out "standard" header. */ /* -------------------------------------------------------------------- */ VSIFPrintf( fpOutput, "%s", "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" ); nSchemaInsertLocation = VSIFTell( fpOutput ); VSIFPrintf( fpOutput, "%s", "<ogr:FeatureCollection\n" ); /* -------------------------------------------------------------------- */ /* Write out schema info if provided in creation options. */ /* -------------------------------------------------------------------- */ const char *pszSchemaURI = CSLFetchNameValue(papszOptions,"XSISCHEMAURI"); const char *pszSchemaOpt = CSLFetchNameValue( papszOptions, "XSISCHEMA" ); if( pszSchemaURI != NULL ) { VSIFPrintf( fpOutput, " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" " xsi:schemaLocation=\"%s\"\n", CSLFetchNameValue( papszOptions, "XSISCHEMAURI" ) ); } else if( pszSchemaOpt == NULL || EQUAL(pszSchemaOpt,"EXTERNAL") ) { char *pszBasename = CPLStrdup(CPLGetBasename( pszName )); VSIFPrintf( fpOutput, " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" " xsi:schemaLocation=\"http://ogr.maptools.org/ %s\"\n", CPLResetExtension( pszBasename, "xsd" ) ); CPLFree( pszBasename ); } VSIFPrintf( fpOutput, "%s", " xmlns:ogr=\"http://ogr.maptools.org/\"\n" ); VSIFPrintf( fpOutput, "%s", " xmlns:gml=\"http://www.opengis.net/gml\">\n" ); /* -------------------------------------------------------------------- */ /* Should we initialize an area to place the boundedBy element? */ /* We will need to seek back to fill it in. */ /* -------------------------------------------------------------------- */ if( CSLFetchBoolean( papszOptions, "BOUNDEDBY", TRUE ) ) { nBoundedByLocation = VSIFTell( fpOutput ); if( nBoundedByLocation != -1 ) VSIFPrintf( fpOutput, "%280s\n", "" ); } else nBoundedByLocation = -1; return TRUE; }
int NTFRecord::ReadPhysicalLine( FILE *fp, char *pszLine ) { int nBytesRead = 0; int nRecordStart, nRecordEnd, i, nLength = 0; /* -------------------------------------------------------------------- */ /* Read enough data that we are sure we have a whole record. */ /* -------------------------------------------------------------------- */ nRecordStart = VSIFTell( fp ); nBytesRead = VSIFRead( pszLine, 1, MAX_RECORD_LEN+2, fp ); if( nBytesRead == 0 ) { if( VSIFEof( fp ) ) return -1; else { CPLError( CE_Failure, CPLE_AppDefined, "Low level read error occured while reading NTF file." ); return -2; } } /* -------------------------------------------------------------------- */ /* Search for CR or LF. */ /* -------------------------------------------------------------------- */ for( i = 0; i < nBytesRead; i++ ) { if( pszLine[i] == 10 || pszLine[i] == 13 ) break; } /* -------------------------------------------------------------------- */ /* If we don't find EOL within 80 characters something has gone */ /* badly wrong! */ /* -------------------------------------------------------------------- */ if( i == MAX_RECORD_LEN+2 ) { CPLError( CE_Failure, CPLE_AppDefined, "%d byte record too long for NTF format.\n" "No line may be longer than 80 characters though up to %d tolerated.\n", nBytesRead, MAX_RECORD_LEN ); return -2; } /* -------------------------------------------------------------------- */ /* Trim CR/LF. */ /* -------------------------------------------------------------------- */ nLength = i; if( pszLine[i+1] == 10 || pszLine[i+1] == 13 ) nRecordEnd = nRecordStart + i + 2; else nRecordEnd = nRecordStart + i + 1; pszLine[nLength] = '\0'; /* -------------------------------------------------------------------- */ /* Restore read pointer to beginning of next record. */ /* -------------------------------------------------------------------- */ VSIFSeek( fp, nRecordEnd, SEEK_SET ); return nLength; }
int GMLReader::LoadClasses( const char *pszFile ) { // Add logic later to determine reasonable default schema file. if( pszFile == NULL ) return FALSE; /* -------------------------------------------------------------------- */ /* Load the raw XML file. */ /* -------------------------------------------------------------------- */ FILE *fp; int nLength; char *pszWholeText; fp = VSIFOpen( pszFile, "rb" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open file %s.", pszFile ); return FALSE; } VSIFSeek( fp, 0, SEEK_END ); nLength = VSIFTell( fp ); VSIFSeek( fp, 0, SEEK_SET ); pszWholeText = (char *) VSIMalloc(nLength+1); if( pszWholeText == NULL ) { CPLError( CE_Failure, CPLE_AppDefined, "Failed to allocate %d byte buffer for %s,\n" "is this really a GMLFeatureClassList file?", nLength, pszFile ); VSIFClose( fp ); return FALSE; } if( VSIFRead( pszWholeText, nLength, 1, fp ) != 1 ) { VSIFree( pszWholeText ); VSIFClose( fp ); CPLError( CE_Failure, CPLE_AppDefined, "Read failed on %s.", pszFile ); return FALSE; } pszWholeText[nLength] = '\0'; VSIFClose( fp ); if( strstr( pszWholeText, "<GMLFeatureClassList>" ) == NULL ) { VSIFree( pszWholeText ); CPLError( CE_Failure, CPLE_AppDefined, "File %s does not contain a GMLFeatureClassList tree.", pszFile ); return FALSE; } /* -------------------------------------------------------------------- */ /* Convert to XML parse tree. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psRoot; psRoot = CPLParseXMLString( pszWholeText ); VSIFree( pszWholeText ); // We assume parser will report errors via CPL. if( psRoot == NULL ) return FALSE; if( psRoot->eType != CXT_Element || !EQUAL(psRoot->pszValue,"GMLFeatureClassList") ) { CPLDestroyXMLNode(psRoot); CPLError( CE_Failure, CPLE_AppDefined, "File %s is not a GMLFeatureClassList document.", pszFile ); return FALSE; } /* -------------------------------------------------------------------- */ /* Extract feature classes for all definitions found. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psThis; for( psThis = psRoot->psChild; psThis != NULL; psThis = psThis->psNext ) { if( psThis->eType == CXT_Element && EQUAL(psThis->pszValue,"GMLFeatureClass") ) { GMLFeatureClass *poClass; poClass = new GMLFeatureClass(); if( !poClass->InitializeFromXML( psThis ) ) { delete poClass; CPLDestroyXMLNode( psRoot ); return FALSE; } poClass->SetSchemaLocked( TRUE ); AddClass( poClass ); } } CPLDestroyXMLNode( psRoot ); SetClassListLocked( TRUE ); return TRUE; }
static void CSVIngest( const char *pszFilename ) { CSVTable *psTable = CSVAccess( pszFilename ); int nFileLen, i, nMaxLineCount, iLine = 0; char *pszThisLine; if( psTable->pszRawData != NULL ) return; /* -------------------------------------------------------------------- */ /* Ingest whole file. */ /* -------------------------------------------------------------------- */ VSIFSeek( psTable->fp, 0, SEEK_END ); nFileLen = VSIFTell( psTable->fp ); VSIRewind( psTable->fp ); psTable->pszRawData = (char *) CPLMalloc(nFileLen+1); if( (int) VSIFRead( psTable->pszRawData, 1, nFileLen, psTable->fp ) != nFileLen ) { CPLFree( psTable->pszRawData ); psTable->pszRawData = NULL; CPLError( CE_Failure, CPLE_FileIO, "Read of file %s failed.", psTable->pszFilename ); return; } psTable->pszRawData[nFileLen] = '\0'; /* -------------------------------------------------------------------- */ /* Get count of newlines so we can allocate line array. */ /* -------------------------------------------------------------------- */ nMaxLineCount = 0; for( i = 0; i < nFileLen; i++ ) { if( psTable->pszRawData[i] == 10 ) nMaxLineCount++; } psTable->papszLines = (char **) CPLCalloc(sizeof(char*),nMaxLineCount); /* -------------------------------------------------------------------- */ /* Build a list of record pointers into the raw data buffer */ /* based on line terminators. Zero terminate the line */ /* strings. */ /* -------------------------------------------------------------------- */ /* skip header line */ pszThisLine = CSVFindNextLine( psTable->pszRawData ); while( pszThisLine != NULL && iLine < nMaxLineCount ) { psTable->papszLines[iLine++] = pszThisLine; pszThisLine = CSVFindNextLine( pszThisLine ); } psTable->nLineCount = iLine; /* -------------------------------------------------------------------- */ /* Allocate and populate index array. Ensure they are in */ /* ascending order so that binary searches can be done on the */ /* array. */ /* -------------------------------------------------------------------- */ psTable->panLineIndex = (int *) CPLMalloc(sizeof(int)*psTable->nLineCount); for( i = 0; i < psTable->nLineCount; i++ ) { psTable->panLineIndex[i] = atoi(psTable->papszLines[i]); if( i > 0 && psTable->panLineIndex[i] < psTable->panLineIndex[i-1] ) { CPLFree( psTable->panLineIndex ); psTable->panLineIndex = NULL; break; } } psTable->iLastLine = -1; /* -------------------------------------------------------------------- */ /* We should never need the file handle against, so close it. */ /* -------------------------------------------------------------------- */ VSIFClose( psTable->fp ); psTable->fp = NULL; }