int TigerFileBase::WriteRecord( char *pachRecord, int nRecLen, const char *pszType, FILE * fp ) { if( fp == NULL ) fp = fpPrimary; pachRecord[0] = *pszType; /* * Prior to TIGER_2002, type 5 files lacked the version. So write * the version in the record iff we're using TIGER_2002 or higher, * or if this is not type "5" */ if ( (poDS->GetVersion() >= TIGER_2002) || (!EQUAL(pszType, "5")) ) { char szVersion[5]; sprintf( szVersion, "%04d", poDS->GetVersionCode() ); strncpy( pachRecord + 1, szVersion, 4 ); } VSIFWrite( pachRecord, nRecLen, 1, fp ); VSIFWrite( (void *) "\r\n", 2, 1, fp ); return TRUE; }
CPLErr ELASRasterBand::IWriteBlock( int nBlockXOff, int nBlockYOff, void * pImage ) { ELASDataset *poGDS = (ELASDataset *) poDS; CPLErr eErr = CE_None; long nOffset; int nDataSize; CPLAssert( nBlockXOff == 0 ); CPLAssert( eAccess == GA_Update ); nDataSize = GDALGetDataTypeSize(eDataType) * poGDS->GetRasterXSize() / 8; nOffset = poGDS->nLineOffset * nBlockYOff + 1024 + (nBand-1) * nDataSize; if( VSIFSeek( poGDS->fp, nOffset, SEEK_SET ) != 0 || VSIFWrite( pImage, 1, nDataSize, poGDS->fp ) != (size_t) nDataSize ) { CPLError( CE_Failure, CPLE_FileIO, "Seek or write of %d bytes at %ld failed.\n", nDataSize, nOffset ); eErr = CE_Failure; } return eErr; }
int OGRFMECacheIndex::Save() { if( hLock == NULL ) return FALSE; /* -------------------------------------------------------------------- */ /* Convert the XML tree into one big character buffer, and */ /* write it out. */ /* -------------------------------------------------------------------- */ char *pszIndexBuffer = CPLSerializeXMLTree( psTree ); if( pszIndexBuffer == NULL ) return FALSE; FILE *fpIndex = VSIFOpen( GetPath(), "wb" ); if( fpIndex == NULL ) return FALSE; VSIFWrite( pszIndexBuffer, 1, strlen(pszIndexBuffer), fpIndex ); CPLFree( pszIndexBuffer ); VSIFClose( fpIndex ); Unlock(); return TRUE; }
OGRErr OGRMILayerAttrIndex::SaveConfigToXML() { if( nIndexCount == 0 ) return OGRERR_NONE; /* -------------------------------------------------------------------- */ /* Create the XML tree corresponding to this layer. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psRoot; psRoot = CPLCreateXMLNode( NULL, CXT_Element, "OGRMILayerAttrIndex" ); CPLCreateXMLElementAndValue( psRoot, "MIIDFilename", CPLGetFilename( pszMIINDFilename ) ); for( int i = 0; i < nIndexCount; i++ ) { OGRMIAttrIndex *poAI = papoIndexList[i]; CPLXMLNode *psIndex; psIndex = CPLCreateXMLNode( psRoot, CXT_Element, "OGRMIAttrIndex" ); CPLCreateXMLElementAndValue( psIndex, "FieldIndex", CPLSPrintf( "%d", poAI->iField ) ); CPLCreateXMLElementAndValue( psIndex, "FieldName", poLayer->GetLayerDefn()->GetFieldDefn(poAI->iField)->GetNameRef() ); CPLCreateXMLElementAndValue( psIndex, "IndexIndex", CPLSPrintf( "%d", poAI->iIndex ) ); } /* -------------------------------------------------------------------- */ /* Save it. */ /* -------------------------------------------------------------------- */ char *pszRawXML = CPLSerializeXMLTree( psRoot ); FILE *fp; CPLDestroyXMLNode( psRoot ); fp = VSIFOpen( pszMetadataFilename, "wb" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to pen `%s' for write.", pszMetadataFilename ); CPLFree( pszRawXML ); return OGRERR_FAILURE; } VSIFWrite( pszRawXML, 1, strlen(pszRawXML), fp ); VSIFClose( fp ); CPLFree( pszRawXML ); return OGRERR_NONE; }
size_t RawRasterBand::Write( void *pBuffer, size_t nSize, size_t nCount ) { if( bIsVSIL ) return VSIFWriteL( pBuffer, nSize, nCount, fpRawL ); else return VSIFWrite( pBuffer, nSize, nCount, fpRaw ); }
void ELASDataset::FlushCache() { GDALDataset::FlushCache(); if( bHeaderModified ) { VSIFSeek( fp, 0, SEEK_SET ); VSIFWrite( &sHeader, 1024, 1, fp ); bHeaderModified = FALSE; } }
void IDADataset::FlushCache() { RawDataset::FlushCache(); if( bHeaderDirty ) { VSIFSeek( fpRaw, 0, SEEK_SET ); VSIFWrite( abyHeader, 512, 1, fpRaw ); bHeaderDirty = FALSE; } }
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 ); }
/********************************************************************** * TABDATFile::Close() * * Close current file, and release all memory used. * * Returns 0 on success, -1 on error. **********************************************************************/ int TABDATFile::Close() { if (m_fp == NULL) return 0; /*---------------------------------------------------------------- * Write access: Update the header with number of records, etc. * and add a CTRL-Z char at the end of the file. *---------------------------------------------------------------*/ if (m_eAccessMode == TABWrite) { WriteHeader(); char cEOF = 26; if (VSIFSeek(m_fp, 0L, SEEK_END) == 0) VSIFWrite(&cEOF, 1, 1, m_fp); } // Delete all structures if (m_poHeaderBlock) { delete m_poHeaderBlock; m_poHeaderBlock = NULL; } if (m_poRecordBlock) { delete m_poRecordBlock; m_poRecordBlock = NULL; } // Close file VSIFClose(m_fp); m_fp = NULL; CPLFree(m_pszFname); m_pszFname = NULL; CPLFree(m_pasFieldDef); m_pasFieldDef = NULL; m_numFields = -1; m_numRecords = -1; m_nFirstRecordPtr = 0; m_nBlockSize = 0; m_nRecordSize = -1; m_nCurRecordId = -1; m_bWriteHeaderInitialized = FALSE; return 0; }
int GMLReader::SaveClasses( const char *pszFile ) { // Add logic later to determine reasonable default schema file. if( pszFile == NULL ) return FALSE; /* -------------------------------------------------------------------- */ /* Create in memory schema tree. */ /* -------------------------------------------------------------------- */ CPLXMLNode *psRoot; psRoot = CPLCreateXMLNode( NULL, CXT_Element, "GMLFeatureClassList" ); for( int iClass = 0; iClass < GetClassCount(); iClass++ ) { GMLFeatureClass *poClass = GetClass( iClass ); CPLAddXMLChild( psRoot, poClass->SerializeToXML() ); } /* -------------------------------------------------------------------- */ /* Serialize to disk. */ /* -------------------------------------------------------------------- */ FILE *fp; int bSuccess = TRUE; char *pszWholeText = CPLSerializeXMLTree( psRoot ); CPLDestroyXMLNode( psRoot ); fp = VSIFOpen( pszFile, "wb" ); if( fp == NULL ) bSuccess = FALSE; else if( VSIFWrite( pszWholeText, strlen(pszWholeText), 1, fp ) != 1 ) bSuccess = FALSE; else VSIFClose( fp ); CPLFree( pszWholeText ); return bSuccess; }
/********************************************************************** * AVCRawBinWriteBytes() * * Write the number of bytes from the buffer to the file. * * If a problem happens, then CPLError() will be called and * CPLGetLastErrNo() can be used to test if a write operation was * successful. **********************************************************************/ void AVCRawBinWriteBytes(AVCRawBinFile *psFile, int nBytesToWrite, const GByte *pBuf) { /*---------------------------------------------------------------- * Make sure file is opened with Write access *---------------------------------------------------------------*/ if (psFile == NULL || (psFile->eAccess != AVCWrite && psFile->eAccess != AVCReadWrite)) { CPLError(CE_Failure, CPLE_FileIO, "AVCRawBinWriteBytes(): call not compatible with access mode."); return; } if (VSIFWrite((void*)pBuf, nBytesToWrite, 1, psFile->fp) != 1) CPLError(CE_Failure, CPLE_FileIO, "Writing to %s failed.", psFile->pszFname); /*---------------------------------------------------------------- * In write mode, we keep track of current file position ( =nbr of * bytes written) through psFile->nCurPos *---------------------------------------------------------------*/ psFile->nCurPos += nBytesToWrite; }
OGRErr OGROCILoaderLayer::WriteFeatureVariableMode( OGRFeature *poFeature ) { OGROCIStringBuf oLine; if( fpData == NULL ) return OGRERR_FAILURE; /* -------------------------------------------------------------------- */ /* Write the FID. */ /* -------------------------------------------------------------------- */ oLine.Append( "00000000" ); oLine.Appendf( 32, " %d|", poFeature->GetFID() ); /* -------------------------------------------------------------------- */ /* Set the geometry */ /* -------------------------------------------------------------------- */ if( poFeature->GetGeometryRef() != NULL) { char szSRID[128]; int nGType; int i; if( nSRID == -1 ) strcpy( szSRID, "NULL" ); else sprintf( szSRID, "%d", nSRID ); if( TranslateToSDOGeometry( poFeature->GetGeometryRef(), &nGType ) == OGRERR_NONE ) { oLine.Appendf( 32, "%d|", nGType ); for( i = 0; i < nElemInfoCount; i++ ) { oLine.Appendf( 32, "%d|", panElemInfo[i] ); } oLine.Append( "/" ); for( i = 0; i < nOrdinalCount; i++ ) { oLine.Appendf( 32, "%.16g|", padfOrdinals[i] ); } oLine.Append( "/" ); } else { oLine.Append( "0|/|/" ); } } else { oLine.Append( "0|/|/" ); } /* -------------------------------------------------------------------- */ /* Set the other fields. */ /* -------------------------------------------------------------------- */ int i; for( i = 0; i < poFeatureDefn->GetFieldCount(); i++ ) { OGRFieldDefn *poFldDefn = poFeatureDefn->GetFieldDefn(i); if( !poFeature->IsFieldSet( i ) ) { if( poFldDefn->GetType() != OFTInteger && poFldDefn->GetType() != OFTReal ) oLine.Append( "0000" ); else oLine.Append( "|" ); continue; } const char *pszStrValue = poFeature->GetFieldAsString(i); if( poFldDefn->GetType() == OFTInteger || poFldDefn->GetType() == OFTReal ) { if( poFldDefn->GetWidth() > 0 && bPreservePrecision && (int) strlen(pszStrValue) > poFldDefn->GetWidth() ) { ReportTruncation( poFldDefn ); oLine.Append( "|" ); } else { oLine.Append( pszStrValue ); oLine.Append( "|" ); } } else { int nLength = strlen(pszStrValue); if( poFldDefn->GetWidth() > 0 && nLength > poFldDefn->GetWidth() ) { ReportTruncation( poFldDefn ); nLength = poFldDefn->GetWidth(); ((char *) pszStrValue)[nLength] = '\0'; } oLine.Appendf( 5, "%04d", nLength ); oLine.Append( pszStrValue ); } } oLine.Appendf( 3, "\n" ); /* -------------------------------------------------------------------- */ /* Update the line's length, and write to disk. */ /* -------------------------------------------------------------------- */ char szLength[9]; size_t nStringLen = strlen(oLine.GetString()); sprintf( szLength, "%08d", (int) (nStringLen-8) ); strncpy( oLine.GetString(), szLength, 8 ); if( VSIFWrite( oLine.GetString(), 1, nStringLen, fpData ) != nStringLen ) { CPLError( CE_Failure, CPLE_FileIO, "Write to loader file failed, likely out of disk space." ); return OGRERR_FAILURE; } else return OGRERR_NONE; }
GDALDataset *IDADataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char ** /* papszParmList */ ) { /* -------------------------------------------------------------------- */ /* Verify input options. */ /* -------------------------------------------------------------------- */ if( eType != GDT_Byte || nBands != 1 ) { CPLError( CE_Failure, CPLE_AppDefined, "Only 1 band, Byte datasets supported for IDA format." ); return NULL; } /* -------------------------------------------------------------------- */ /* Try to create the file. */ /* -------------------------------------------------------------------- */ FILE *fp; fp = VSIFOpen( pszFilename, "wb" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.\n", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Prepare formatted header. */ /* -------------------------------------------------------------------- */ GByte abyHeader[512]; memset( abyHeader, 0, sizeof(abyHeader) ); abyHeader[22] = 200; /* image type - CALCULATED */ abyHeader[23] = 0; /* projection - NONE */ abyHeader[30] = nYSize % 256; abyHeader[31] = (GByte) (nYSize / 256); abyHeader[32] = nXSize % 256; abyHeader[33] = (GByte) (nXSize / 256); abyHeader[170] = 255; /* missing = 255 */ c2tp( 1.0, abyHeader + 171 ); /* slope = 1.0 */ c2tp( 0.0, abyHeader + 177 ); /* offset = 0 */ abyHeader[168] = 0; // lower limit abyHeader[169] = 254; // upper limit // pixel size = 1.0 c2tp( 1.0, abyHeader + 144 ); c2tp( 1.0, abyHeader + 150 ); if( VSIFWrite( abyHeader, 1, 512, fp ) != 512 ) { CPLError( CE_Failure, CPLE_AppDefined, "IO error writing %s.\n%s", pszFilename, VSIStrerror( errno ) ); VSIFClose( fp ); return NULL; } /* -------------------------------------------------------------------- */ /* Now we need to extend the file to just the right number of */ /* bytes for the data we have to ensure it will open again */ /* properly. */ /* -------------------------------------------------------------------- */ if( VSIFSeek( fp, nXSize * nYSize - 1, SEEK_CUR ) != 0 || VSIFWrite( abyHeader, 1, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_AppDefined, "IO error writing %s.\n%s", pszFilename, VSIStrerror( errno ) ); VSIFClose( fp ); return NULL; } VSIFClose( fp ); return (GDALDataset *) GDALOpen( pszFilename, GA_Update ); }
size_t VSIFWriteL( void * pBuffer, size_t nSize, size_t nCount, FILE * fp ) { return VSIFWrite( pBuffer, nSize, nCount, fp ); }
GDALDataset *ELASDataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char ** /* notdef: papszParmList */ ) { int nBandOffset; /* -------------------------------------------------------------------- */ /* Verify input options. */ /* -------------------------------------------------------------------- */ if (nBands <= 0) { CPLError( CE_Failure, CPLE_NotSupported, "ELAS driver does not support %d bands.\n", nBands); return NULL; } if( eType != GDT_Byte && eType != GDT_Float32 && eType != GDT_Float64 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create an ELAS dataset with an illegal\n" "data type (%d).\n", eType ); return NULL; } /* -------------------------------------------------------------------- */ /* Try to create the file. */ /* -------------------------------------------------------------------- */ FILE *fp; fp = VSIFOpen( pszFilename, "w" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.\n", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* How long will each band of a scanline be? */ /* -------------------------------------------------------------------- */ nBandOffset = nXSize * GDALGetDataTypeSize(eType)/8; if( nBandOffset % 256 != 0 ) { nBandOffset = nBandOffset - (nBandOffset % 256) + 256; } /* -------------------------------------------------------------------- */ /* Setup header data block. */ /* */ /* Note that CPL_MSBWORD32() will swap little endian words to */ /* big endian on little endian platforms. */ /* -------------------------------------------------------------------- */ ELASHeader sHeader; memset( &sHeader, 0, 1024 ); sHeader.NBIH = CPL_MSBWORD32(1024); sHeader.NBPR = CPL_MSBWORD32(nBands * nBandOffset); sHeader.IL = CPL_MSBWORD32(1); sHeader.LL = CPL_MSBWORD32(nYSize); sHeader.IE = CPL_MSBWORD32(1); sHeader.LE = CPL_MSBWORD32(nXSize); sHeader.NC = CPL_MSBWORD32(nBands); sHeader.H4321 = CPL_MSBWORD32(4321); sHeader.IH19[0] = 0x04; sHeader.IH19[1] = 0xd2; sHeader.IH19[3] = (GByte) (GDALGetDataTypeSize(eType) / 8); if( eType == GDT_Byte ) sHeader.IH19[2] = 1 << 2; else if( eType == GDT_Float32 ) sHeader.IH19[2] = 16 << 2; else if( eType == GDT_Float64 ) sHeader.IH19[2] = 17 << 2; /* -------------------------------------------------------------------- */ /* Write the header data. */ /* -------------------------------------------------------------------- */ VSIFWrite( &sHeader, 1024, 1, fp ); /* -------------------------------------------------------------------- */ /* Now write out zero data for all the imagery. This is */ /* inefficient, but simplies the IReadBlock() / IWriteBlock() logic.*/ /* -------------------------------------------------------------------- */ GByte *pabyLine; pabyLine = (GByte *) CPLCalloc(nBandOffset,nBands); for( int iLine = 0; iLine < nYSize; iLine++ ) { if( VSIFWrite( pabyLine, 1, nBandOffset, fp ) != (size_t) nBandOffset ) { CPLError( CE_Failure, CPLE_FileIO, "Error writing ELAS image data ... likely insufficient" " disk space.\n" ); VSIFClose( fp ); CPLFree( pabyLine ); return NULL; } } CPLFree( pabyLine ); VSIFClose( fp ); /* -------------------------------------------------------------------- */ /* Try to return a regular handle on the file. */ /* -------------------------------------------------------------------- */ return (GDALDataset *) GDALOpen( pszFilename, GA_Update ); }
int DDFModule::Create( const char *pszFilename ) { CPLAssert( fpDDF == NULL ); /* -------------------------------------------------------------------- */ /* Create the file on disk. */ /* -------------------------------------------------------------------- */ fpDDF = VSIFOpen( pszFilename, "wb+" ); if( fpDDF == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to create file %s, check path and permissions.", pszFilename ); return FALSE; } bReadOnly = FALSE; /* -------------------------------------------------------------------- */ /* Prepare all the field definition information. */ /* -------------------------------------------------------------------- */ int iField; _fieldControlLength = 9; _recLength = 24 + nFieldDefnCount * (_sizeFieldLength+_sizeFieldPos+_sizeFieldTag) + 1; _fieldAreaStart = _recLength; for( iField=0; iField < nFieldDefnCount; iField++ ) { int nLength; papoFieldDefns[iField]->GenerateDDREntry( NULL, &nLength ); _recLength += nLength; } /* -------------------------------------------------------------------- */ /* Setup 24 byte leader. */ /* -------------------------------------------------------------------- */ char achLeader[25]; sprintf( achLeader+0, "%05d", (int) _recLength ); achLeader[5] = _interchangeLevel; achLeader[6] = _leaderIden; achLeader[7] = _inlineCodeExtensionIndicator; achLeader[8] = _versionNumber; achLeader[9] = _appIndicator; sprintf( achLeader+10, "%02d", (int) _fieldControlLength ); sprintf( achLeader+12, "%05d", (int) _fieldAreaStart ); strncpy( achLeader+17, _extendedCharSet, 3 ); sprintf( achLeader+20, "%1d", (int) _sizeFieldLength ); sprintf( achLeader+21, "%1d", (int) _sizeFieldPos ); achLeader[22] = '0'; sprintf( achLeader+23, "%1d", (int) _sizeFieldTag ); VSIFWrite( achLeader, 24, 1, fpDDF ); /* -------------------------------------------------------------------- */ /* Write out directory entries. */ /* -------------------------------------------------------------------- */ int nOffset = 0; for( iField=0; iField < nFieldDefnCount; iField++ ) { char achDirEntry[12]; int nLength; papoFieldDefns[iField]->GenerateDDREntry( NULL, &nLength ); strcpy( achDirEntry, papoFieldDefns[iField]->GetName() ); sprintf( achDirEntry + _sizeFieldTag, "%03d", nLength ); sprintf( achDirEntry + _sizeFieldTag + _sizeFieldLength, "%04d", nOffset ); nOffset += nLength; VSIFWrite( achDirEntry, 11, 1, fpDDF ); } char chUT = DDF_FIELD_TERMINATOR; VSIFWrite( &chUT, 1, 1, fpDDF ); /* -------------------------------------------------------------------- */ /* Write out the field descriptions themselves. */ /* -------------------------------------------------------------------- */ for( iField=0; iField < nFieldDefnCount; iField++ ) { char *pachData; int nLength; papoFieldDefns[iField]->GenerateDDREntry( &pachData, &nLength ); VSIFWrite( pachData, nLength, 1, fpDDF ); CPLFree( pachData ); } return TRUE; }
/********************************************************************** * 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; }
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 ); }
OGRErr OGROCILoaderLayer::WriteFeatureStreamMode( OGRFeature *poFeature ) { /* -------------------------------------------------------------------- */ /* Write the FID. */ /* -------------------------------------------------------------------- */ VSIFPrintf( fpLoader, " %ld|", poFeature->GetFID() ); /* -------------------------------------------------------------------- */ /* Set the geometry */ /* -------------------------------------------------------------------- */ int nLineLen = 0; if( poFeature->GetGeometryRef() != NULL) { char szSRID[128]; int nGType; int i; if( nSRID == -1 ) strcpy( szSRID, "NULL" ); else sprintf( szSRID, "%d", nSRID ); if( TranslateToSDOGeometry( poFeature->GetGeometryRef(), &nGType ) == OGRERR_NONE ) { VSIFPrintf( fpLoader, "%d|", nGType ); for( i = 0; i < nElemInfoCount; i++ ) { VSIFPrintf( fpLoader, "%d|", panElemInfo[i] ); if( ++nLineLen > 18 && i < nElemInfoCount-1 ) { VSIFPrintf( fpLoader, "\n#" ); nLineLen = 0; } } VSIFPrintf( fpLoader, "/" ); for( i = 0; i < nOrdinalCount; i++ ) { VSIFPrintf( fpLoader, "%.16g|", padfOrdinals[i] ); if( ++nLineLen > 6 && i < nOrdinalCount-1 ) { VSIFPrintf( fpLoader, "\n#" ); nLineLen = 0; } } VSIFPrintf( fpLoader, "/" ); } else { VSIFPrintf( fpLoader, "0|/|/" ); } } else { VSIFPrintf( fpLoader, "0|/|/" ); } /* -------------------------------------------------------------------- */ /* Set the other fields. */ /* -------------------------------------------------------------------- */ int i; nLineLen = 0; VSIFPrintf( fpLoader, "\n#" ); for( i = 0; i < poFeatureDefn->GetFieldCount(); i++ ) { OGRFieldDefn *poFldDefn = poFeatureDefn->GetFieldDefn(i); if( !poFeature->IsFieldSet( i ) ) { if( poFldDefn->GetType() != OFTInteger && poFldDefn->GetType() != OFTReal ) VSIFPrintf( fpLoader, "%04d", 0 ); continue; } const char *pszStrValue = poFeature->GetFieldAsString(i); if( nLineLen > 70 ) { VSIFPrintf( fpLoader, "\n#" ); nLineLen = 0; } nLineLen += strlen(pszStrValue); if( poFldDefn->GetType() == OFTInteger || poFldDefn->GetType() == OFTReal ) { if( poFldDefn->GetWidth() > 0 && bPreservePrecision && (int) strlen(pszStrValue) > poFldDefn->GetWidth() ) { ReportTruncation( poFldDefn ); VSIFPrintf( fpLoader, "|" ); } else VSIFPrintf( fpLoader, "%s|", pszStrValue ); } else { int nLength = strlen(pszStrValue); if( poFldDefn->GetWidth() > 0 && nLength > poFldDefn->GetWidth() ) { ReportTruncation( poFldDefn ); nLength = poFldDefn->GetWidth(); } VSIFPrintf( fpLoader, "%04d", nLength ); VSIFWrite( (void *) pszStrValue, 1, nLength, fpLoader ); } } if( VSIFPrintf( fpLoader, "\n" ) == 0 ) { CPLError( CE_Failure, CPLE_FileIO, "Write to loader file failed, likely out of disk space." ); return OGRERR_FAILURE; } else return OGRERR_NONE; }
OGRLayer * OGRShapeDataSource::CreateLayer( const char * pszLayerName, OGRSpatialReference *poSRS, OGRwkbGeometryType eType, char ** papszOptions ) { SHPHandle hSHP; DBFHandle hDBF; int nShapeType; /* -------------------------------------------------------------------- */ /* Verify we are in update mode. */ /* -------------------------------------------------------------------- */ if( !bDSUpdate ) { CPLError( CE_Failure, CPLE_NoWriteAccess, "Data source %s opened read-only.\n" "New layer %s cannot be created.\n", pszName, pszLayerName ); return NULL; } /* -------------------------------------------------------------------- */ /* Figure out what type of layer we need. */ /* -------------------------------------------------------------------- */ if( eType == wkbUnknown || eType == wkbLineString ) nShapeType = SHPT_ARC; else if( eType == wkbPoint ) nShapeType = SHPT_POINT; else if( eType == wkbPolygon ) nShapeType = SHPT_POLYGON; else if( eType == wkbMultiPoint ) nShapeType = SHPT_MULTIPOINT; else if( eType == wkbPoint25D ) nShapeType = SHPT_POINTZ; else if( eType == wkbLineString25D ) nShapeType = SHPT_ARCZ; else if( eType == wkbMultiLineString ) nShapeType = SHPT_ARC; else if( eType == wkbMultiLineString25D ) nShapeType = SHPT_ARCZ; else if( eType == wkbPolygon25D ) nShapeType = SHPT_POLYGONZ; else if( eType == wkbMultiPolygon ) nShapeType = SHPT_POLYGON; else if( eType == wkbMultiPolygon25D ) nShapeType = SHPT_POLYGONZ; else if( eType == wkbMultiPoint25D ) nShapeType = SHPT_MULTIPOINTZ; else if( eType == wkbNone ) nShapeType = SHPT_NULL; else nShapeType = -1; /* -------------------------------------------------------------------- */ /* Has the application overridden this with a special creation */ /* option? */ /* -------------------------------------------------------------------- */ const char *pszOverride = CSLFetchNameValue( papszOptions, "SHPT" ); if( pszOverride == NULL ) /* ignore */; else if( EQUAL(pszOverride,"POINT") ) { nShapeType = SHPT_POINT; eType = wkbPoint; } else if( EQUAL(pszOverride,"ARC") ) { nShapeType = SHPT_ARC; eType = wkbLineString; } else if( EQUAL(pszOverride,"POLYGON") ) { nShapeType = SHPT_POLYGON; eType = wkbPolygon; } else if( EQUAL(pszOverride,"MULTIPOINT") ) { nShapeType = SHPT_MULTIPOINT; eType = wkbMultiPoint; } else if( EQUAL(pszOverride,"POINTZ") ) { nShapeType = SHPT_POINTZ; eType = wkbPoint25D; } else if( EQUAL(pszOverride,"ARCZ") ) { nShapeType = SHPT_ARCZ; eType = wkbLineString25D; } else if( EQUAL(pszOverride,"POLYGONZ") ) { nShapeType = SHPT_POLYGONZ; eType = wkbPolygon25D; } else if( EQUAL(pszOverride,"MULTIPOINTZ") ) { nShapeType = SHPT_MULTIPOINTZ; eType = wkbMultiPoint25D; } else if( EQUAL(pszOverride,"NONE") ) { nShapeType = SHPT_NULL; } else { CPLError( CE_Failure, CPLE_NotSupported, "Unknown SHPT value of `%s' passed to Shapefile layer\n" "creation. Creation aborted.\n", pszOverride ); return NULL; } if( nShapeType == -1 ) { CPLError( CE_Failure, CPLE_NotSupported, "Geometry type of `%s' not supported in shapefiles.\n" "Type can be overridden with a layer creation option\n" "of SHPT=POINT/ARC/POLYGON/MULTIPOINT/POINTZ/ARCZ/POLYGONZ/MULTIPOINTZ.\n", OGRGeometryTypeToName(eType) ); return NULL; } /* -------------------------------------------------------------------- */ /* What filename do we use, excluding the extension? */ /* -------------------------------------------------------------------- */ char *pszBasename; if( bSingleNewFile && nLayers == 0 ) { char *pszPath = CPLStrdup(CPLGetPath(pszName)); char *pszFBasename = CPLStrdup(CPLGetBasename(pszName)); pszBasename = CPLStrdup(CPLFormFilename(pszPath, pszFBasename, NULL)); CPLFree( pszFBasename ); CPLFree( pszPath ); } else if( bSingleNewFile ) { char *pszPath = CPLStrdup(CPLGetPath(pszName)); pszBasename = CPLStrdup(CPLFormFilename(pszPath,pszLayerName,NULL)); CPLFree( pszPath ); } else pszBasename = CPLStrdup(CPLFormFilename(pszName,pszLayerName,NULL)); /* -------------------------------------------------------------------- */ /* Create the shapefile. */ /* -------------------------------------------------------------------- */ char *pszFilename; if( nShapeType != SHPT_NULL ) { pszFilename = CPLStrdup(CPLFormFilename( NULL, pszBasename, "shp" )); hSHP = SHPCreate( pszFilename, nShapeType ); if( hSHP == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open Shapefile `%s'.\n", pszFilename ); CPLFree( pszFilename ); CPLFree( pszBasename ); return NULL; } CPLFree( pszFilename ); } else hSHP = NULL; /* -------------------------------------------------------------------- */ /* Create a DBF file. */ /* -------------------------------------------------------------------- */ pszFilename = CPLStrdup(CPLFormFilename( NULL, pszBasename, "dbf" )); hDBF = DBFCreate( pszFilename ); if( hDBF == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open Shape DBF file `%s'.\n", pszFilename ); CPLFree( pszFilename ); CPLFree( pszBasename ); return NULL; } CPLFree( pszFilename ); /* -------------------------------------------------------------------- */ /* Create the .prj file, if required. */ /* -------------------------------------------------------------------- */ if( poSRS != NULL ) { char *pszWKT = NULL; CPLString osPrjFile = CPLFormFilename( NULL, pszBasename, "prj"); FILE *fp; /* the shape layer needs it's own copy */ poSRS = poSRS->Clone(); poSRS->morphToESRI(); if( poSRS->exportToWkt( &pszWKT ) == OGRERR_NONE && (fp = VSIFOpen( osPrjFile, "wt" )) != NULL ) { VSIFWrite( pszWKT, strlen(pszWKT), 1, fp ); VSIFClose( fp ); } CPLFree( pszWKT ); poSRS->morphFromESRI(); } /* -------------------------------------------------------------------- */ /* Create the layer object. */ /* -------------------------------------------------------------------- */ OGRShapeLayer *poLayer; poLayer = new OGRShapeLayer( pszBasename, hSHP, hDBF, poSRS, TRUE, eType ); poLayer->InitializeIndexSupport( pszBasename ); CPLFree( pszBasename ); /* -------------------------------------------------------------------- */ /* Add layer to data source layer list. */ /* -------------------------------------------------------------------- */ papoLayers = (OGRShapeLayer **) CPLRealloc( papoLayers, sizeof(OGRShapeLayer *) * (nLayers+1) ); papoLayers[nLayers++] = poLayer; return poLayer; }