CFile:Read


The Read method reads data from a CFile object in which the file was opened in binary mode ("rb"). This method can read 1 value or a table of values of a specified data type. The number of values to read is given by nCount. If nCount is not specified, then 1 value is read. However, reading a character string is a special case, as described below. Also see the ReadBswap method for reading data using a reversed byte order

Syntax

nValue = CFile:Read( sDataType )

sString = CFile:Read( "str" )

sString = CFile:Read( "str", nCount )

nTable = CFile:Read( sDataType, nCount )

where

    sDataType specifies the kind of data to read, such as "short", "int", or "double". One value will be returned as a number or string, depending on the data type (see below).

    If sDataType is "str", then nCount is an optional argument that specifies the number of characters to return. If not specified, the string will read up to the first null character that terminates the string.

    If nCount is specified and sDataType is not "str", as in the last form, then nCount values are returned in a Lua table.

  

See Mira Data Types for a description of the options for the sDataType parameter. The data type determines whether a value is returned as a number or a string:

    Data types that return a number or table of numbers:

"byte", "short", "ushort", "int", "float", and "double".

    Data types that return a string or a table or strings:

"rgb", "urgb", "lrgb", "frgb", and "drgb", and "str".

Reading strings

Reading a "str" value is a special case in which multiple values (characters) are not returned as a Lua table. In addition, a string may be self-terminated by a null character or you can specify the number of characters to read. If you do not specify the nCount value, then Mira reads the string until the first null-character is read, which indicates the end of the string. If nCount is specified, then nCount characters will be returned unless a null-character is encountered first. If you want to read just one character, use Read("str",1). Do not use Read("byte") to read 1 character because that returns a numeric value rather than a character.

Example

The following script shows how to read values from the beginning of a raw 2-dimensional data file. The number of columns and rows are stored as 32-bit integer values at the beginning of the file, followed by the data as 32-bit float values. Assume the file named sFileName exists:

local F = FileOpen(sFileName, "rb")

-- open the file and create a CFile object

if F ~= nil then

-- file was opened successfully

  local nCols = F:Read("int")

-- read a 32-bit integer value

  local nRows = F:Read("int")

-- read a 32-bit integer value

  local t = F:Read("float",nCols*nRows)

-- read (nCols*nRows) values into a table

end

 

Related Topics

Write

ReadBswap

CFile Class