FileSystem.FilePutObject(Int32, Object, Int64) Método
Definição
Grava dados de uma variável em um arquivo de disco.Writes data from a variable to a disk file. O recurso My oferece melhor produtividade e desempenho em operações de E/S do arquivo do que FilePutObject.The My feature gives you better productivity and performance in file I/O operations than FilePutObject. Para obter mais informações, consulte FileSystem.For more information, see FileSystem.
public static void FilePutObject (int FileNumber, object Value, long RecordNumber = -1);
static member FilePutObject : int * obj * int64 -> unit
Public Sub FilePutObject (FileNumber As Integer, Value As Object, Optional RecordNumber As Long = -1)
Parâmetros
- FileNumber
- Int32
Obrigatórios.Required. Qualquer número de arquivo válido.Any valid file number.
- Value
- Object
Obrigatórios.Required. Nome de variável válido que contém dados gravados em disco.Valid variable name that contains data written to disk.
- RecordNumber
- Int64
Opcional.Optional. Registre o número (arquivos de modo Random) ou número de byte (arquivos de modo Binary) no qual a gravação começa.Record number (Random mode files) or byte number (Binary mode files) at which writing starts.
Exemplos
Este exemplo usa a FilePutObject função para gravar uma cadeia de caracteres em um arquivo.This example uses the FilePutObject function to write a string to a file.
Sub WriteData()
Dim text As String = "test"
FileOpen(1, "test.bin", OpenMode.Binary)
FilePutObject(1, text)
FileClose(1)
End Sub
Comentários
A FilePutObject função é usada em vez de FilePut para evitar ambigüidades em tempo de compilação se o tipo Object for passado em vez de outro tipo, como,, Integer Long Short e assim por diante.The FilePutObject function is used instead of FilePut to avoid ambiguities at compile time if type Object is passed instead of another type, such as Integer, Long, Short, and so forth.
FilePutObject grava e lê os descritores que descrevem o objeto.FilePutObject writes and reads descriptors that describe the object. Se você pretende gravar o Variant tipo, FilePutObject é necessário.If you intend to write out the Variant type, FilePutObject is required. Em caso de dúvida, se você estiver usando um objeto para o segundo parâmetro, recomendamos que sempre use o FilePutObject e o FileGetObject .When in doubt, if you are using an object for the second parameter, we recommend that you always use FilePutObject and FileGetObject.
FilePutObject é válido somente no Random Binary modo e.FilePutObject is valid only in Random and Binary mode.
Dados gravados com FilePutObject costumam ser lidos a partir de um arquivo usando FileGetObject.Data written with FilePutObject is usually read from a file by using FileGetObject.
O primeiro registro ou byte em um arquivo está na posição 1, o segundo registro ou byte está na posição 2 e assim por diante.The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. Se você omitir RecordNumber , o gravará FilePutObject o próximo registro ou byte após o último FileGetObject ou FilePutObject a função (ou o registro ou byte apontado pela última Seek função).If you omit RecordNumber, FilePutObject writes the next record or byte after the last FileGetObject or FilePutObject function (or the record or byte pointed to by the last Seek function).
O argumento StringIsFixedLength controla se a função interpreta cadeias de caracteres como sendo de tamanho variável ou fixo.The StringIsFixedLength argument controls whether the function interprets strings as variable or fixed length. FilePutObject não grava o descritor de comprimento quando o argumento é True .FilePutObject does not write the length descriptor when the argument is True. Se você usar StringIsFixedLength = True FilePutObject o com o, precisará fazer o mesmo com o FileGetObject , e também deverá certificar-se de que a cadeia de caracteres seja inicializada com o comprimento esperado.If you use StringIsFixedLength = True with FilePutObject, you have to do the same with FileGetObject, and you must also make sure that the string is initialized to the length expected.
Modo aleatórioRandom Mode
Para arquivos abertos no Random modo, as seguintes regras se aplicam:For files opened in Random mode, the following rules apply:
Se o comprimento dos dados que estão sendo gravados for menor que o comprimento especificado na
RecordLengthcláusula daFileOpenfunção, oFilePutObjectgravará os registros subsequentes em limites de tamanho de registro.If the length of the data being written is less than the length specified in theRecordLengthclause of theFileOpenfunction,FilePutObjectwrites subsequent records on record-length boundaries. O espaço entre o final de um registro e o início do próximo registro é preenchido com o conteúdo existente do buffer de arquivo.The space between the end of one record and the start of the next record is padded with the existing contents of the file buffer. Como a quantidade de dados de preenchimento não pode ser determinada com precisão, geralmente é uma boa ideia ter o tamanho do registro correspondente ao comprimento dos dados que estão sendo gravados.Because the amount of padding data cannot be precisely determined, it is generally a good idea to have the record length match the length of the data being written. Se o comprimento dos dados que estão sendo gravados for maior que o comprimento especificado naRecordLengthcláusula daFileOpenfunção, uma exceção será lançada.If the length of the data being written is greater than the length specified in theRecordLengthclause of theFileOpenfunction, an exception is thrown.Caso a variável que está sendo gravada seja um objeto que contém um tipo numérico,
FilePutObjectgrava dois bytes que identificam oVarTypedo objeto e, em seguida, grava a variável.If the variable being written is an object that contains a numeric type,FilePutObjectwrites two bytes identifying theVarTypeof the object and then writes the variable. Por exemplo, ao gravar um objeto que contém um inteiro, oFilePutObjectgrava seis bytes: dois bytes que identificam o objeto comoVarType(3)(Integer) e quatro bytes que contêm os dados.For example, when writing an object that contains an integer,FilePutObjectwrites six bytes: two bytes that identify the object asVarType(3)(Integer) and four bytes that contain the data. O tamanho do registro especificado peloRecordLengthparâmetro naFileOpenfunção deve ser pelo menos dois bytes maiores do que o número real de bytes necessários para armazenar a variável.The record length specified by theRecordLengthparameter in theFileOpenfunction must be at least two bytes greater than the actual number of bytes required to store the variable.Se a variável que está sendo gravada for um objeto que contém uma cadeia de caracteres, o
FilePutObjectgravará um descritor de dois bytes que identifica oVarType(8)do objeto, um descritor de dois bytes que indica o comprimento da cadeia de caracteres e, em seguida, gravará os dados da cadeia de caracteres.If the variable being written is an object that contains a string,FilePutObjectwrites a two-byte descriptor identifying theVarType(8)of the object, a two-byte descriptor indicating the length of the string, and then writes the string data. O tamanho do registro especificado peloRecordLengthparâmetro naFileOpenfunção deve ser pelo menos quatro bytes maior que o comprimento real da cadeia de caracteres.The record length specified by theRecordLengthparameter in theFileOpenfunction must be at least four bytes greater than the actual length of the string. Caso queira colocar uma cadeia de caracteres sem o descritor, você deve passarTruepara o parâmetroStringIsFixedLength, e a cadeia de caracteres lida deve ter o tamanho correto.If you want to put a string without the descriptor, you should passTrueto theStringIsFixedLengthparameter, and the string you read into should be the correct length.Se a variável que está sendo gravada for uma matriz, o tamanho do registro especificado pela
RecordLengthcláusula naFileOpenfunção deverá ser maior ou igual à soma de todos os bytes necessários para gravar os dados da matriz e o descritor de matriz.If the variable being written is an array, then the record length specified by theRecordLengthclause in theFileOpenfunction must be greater than or equal to the sum of all the bytes required to write the array data and the array descriptor. O descritor especifica a classificação da matriz, o tamanho e os limites inferiores para cada classificação.The descriptor specifies the rank of the array, the size, and the lower bounds for each rank. Seu comprimento é igual a 2 mais 8 vezes o número de dimensões: (2 + 8 * NumberOfDimensions).Its length equals 2 plus 8 times the number of dimensions: (2 + 8 * NumberOfDimensions).
Modo binárioBinary Mode
Para arquivos abertos no Binary modo, todas as Random regras de modo se aplicam, exceto:For files opened in Binary mode, all the Random mode rules apply, except:
- A cláusula
RecordLengthna função deFileOpennão está em vigor.TheRecordLengthclause in theFileOpenfunction has no effect.FilePutObjectgrava todas as variáveis em disco de forma contígua, ou seja, sem preenchimento entre os registros.FilePutObjectwrites all variables to disk contiguously, that is, without padding between records.