FileOpen


This global function opens a file and returns a new CFile object for use in working with the file. This function is not a class member but it provides an alternative to using the pair of commands, CFile:new followed by CFile:Open. This method creates and returns a CFile object for working with the open file.

Syntax

CFile = FileOpen( sFileName, sMode )

where

    sFileName is the full path name for the file to be opened.

    sMode is the file mode (see below).

    CFile is a new CFile object returned by this function. On failure, nil is returned.

  

This function can open the file in either text or binary mode for reading, writing, or appending. The modes and how to specify them are described under CFile Access Modes.

When the script is finished with the file, the CFile object created by this function should closed using either the Close or delete destructor.

Example

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

The nCols and nRows values are written individually as "int" data type, meaning 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

-- return if a table was not passed

 local sName = GetFileNameSave( "dat" )

-- open a file with file type "dat"

 if sName ~= nil then

-- be sure a file name was selected

  local F = FileOpen( sName, "wb" )

-- Open the file for writing binary

  if F ~= nil then

-- if the file was opened

   F:Write( nCols, "int" )

-- number of columns as an integer

   F:Write( nRows, "int" )

-- number of rows as an 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

File Access Modes

GetFileNameSave

CFile class (class-based file opening)