CFile:Write


The Write method writes binary data to a file opened in binary mode. The format to use for writing the value or table elements is specified by the sDataType parameter. Also see the WriteBswap method for writing data with a reversed byte order.

Syntax

nBytes = CFile:Write( value, sDataType )

nBytes = CFile:Write( table )

nBytes = CFile:Write( table, sDataType )

where

    value is a value to be written to the file.

    table is a Lua table of 1-dimension to be written to the file. The table cannot contain nested tables, must start at index [1], and must have sequential indices up through [ number of elements ].

    sDataType is a string that specifies the data format used to write the value or the table elements to the file. When writing a Lua table, sDataType is optional and defaults to "double" (i.e., 64-bit real values) if not specified.

    The return value nBytes is the number of bytes written to the file.

  

This method can write single values or an entire data table to the CFile object. The format used in the output file is not necessarily the same as that of the value being written. For example, suppose value = 12. Then you can write this value as an 8-, 16-, or 32-bit integer or a 32- or 64 bit real number by changing the sDataType string. See Data Types for a description of the available data types and the string to use for sDataType.

Example

The script below provides a complete function to save a Lua table to a raw binary file as 64-bit real numbers. The table is a simple array with indices [1] through [ nCols x nRows ].

The nCols and nRows parameters are written individually as "int" (32 bit) integers. Following that is a numeric Data Type code to indicate the table contains 64 bit real numbers. Then the entire table is saved. When using Write for a table, the output data type defaults to 64-bit real values if it is not specified. For the file to end up with the correct length, it is assumed that the number of table elements is nCols x nRows.

function Write2dTable( t, nCols, nRows )

 

 if type(t)~="table" then return false end

-- failure: a table was not passed

 local sName = GetFileNameSave( "dat" )

-- Get a file name with file type "dat"

 if sName ~= nil then

-- check that a file name was selected

  F = FileOpen( sName, "wb" )

-- Open the file for writing

  if F ~= nil then

-- if the file was opened

   F:Write( nCols, "int" )

-- number of columns as a long integer

   F:Write( nRows, "int" )

-- number of rows as a long integer

   F:Write( 6, "int" )

-- 6 = code for 64-bit real number

   F:Write( t )

-- write the table as 64-bit real

   F:Close()

-- close the file when done

   return true

-- success

  end

 

 end

 

 return false

-- failure

end

 

Related Topics

Read

WriteBswap

File Access Modes

GetFileNameSave

CFile Class