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 RecordLength cláusula da FileOpen função, o FilePutObject gravará os registros subsequentes em limites de tamanho de registro.If the length of the data being written is less than the length specified in the RecordLength clause of the FileOpen function, FilePutObject writes 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 na RecordLength cláusula da FileOpen função, uma exceção será lançada.If the length of the data being written is greater than the length specified in the RecordLength clause of the FileOpen function, an exception is thrown.

  • Caso a variável que está sendo gravada seja um objeto que contém um tipo numérico, FilePutObject grava dois bytes que identificam o VarType do objeto e, em seguida, grava a variável.If the variable being written is an object that contains a numeric type, FilePutObject writes two bytes identifying the VarType of the object and then writes the variable. Por exemplo, ao gravar um objeto que contém um inteiro, o FilePutObject grava seis bytes: dois bytes que identificam o objeto como VarType(3) ( Integer ) e quatro bytes que contêm os dados.For example, when writing an object that contains an integer, FilePutObject writes six bytes: two bytes that identify the object as VarType(3) (Integer) and four bytes that contain the data. O tamanho do registro especificado pelo RecordLength parâmetro na FileOpen funçã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 the RecordLength parameter in the FileOpen function 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 FilePutObject gravará um descritor de dois bytes que identifica o VarType(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, FilePutObject writes a two-byte descriptor identifying the VarType(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 pelo RecordLength parâmetro na FileOpen função deve ser pelo menos quatro bytes maior que o comprimento real da cadeia de caracteres.The record length specified by the RecordLength parameter in the FileOpen function 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 passar True para o parâmetro StringIsFixedLength, e a cadeia de caracteres lida deve ter o tamanho correto.If you want to put a string without the descriptor, you should pass True to the StringIsFixedLength parameter, 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 RecordLength cláusula na FileOpen funçã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 the RecordLength clause in the FileOpen function 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 RecordLength na função de FileOpen não está em vigor.The RecordLength clause in the FileOpen function has no effect. FilePutObject grava todas as variáveis em disco de forma contígua, ou seja, sem preenchimento entre os registros.FilePutObject writes all variables to disk contiguously, that is, without padding between records.

Aplica-se a

Confira também