MTA:Eir/FileSystem/file/write

From Multi Theft Auto: Wiki
Revision as of 23:49, 30 January 2014 by The GTA (talk | contribs) (Created page with "__NOTOC__ This function attempts to write a string of bytes (characters) into the file. It returns the amount of bytes that have actually been written. ==Syntax== <syntaxhighlight lang="lua"> ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

This function attempts to write a string of bytes (characters) into the file. It returns the amount of bytes that have actually been written.

Syntax

int file.write ( string dataString )

Arguments

  • dataString: the string of data that should be written into the file

Returns

Returns the amount of bytes that have been actually written into the file. Returns false if dataString is not a valid string.

Example

Click to collapse [-]
Client

This snippet logs the local player's chat output into a file.

-- Open up the logfile.
-- If it was not created already, create it.
local logFile = false;

if ( fileExists( "log.dat" ) ) then
    logFile = fileOpen( "log.dat" );
else
    logFile = fileCreate( "log.dat" );
end

-- Table of all log entries.
-- The logfile has to be written at the destruction of the resource environment.
-- This is done so we can have multiple log sessions added into a file stream.
local logEntries = {};

-- Function to append entries into the logfile.
local function addLogEntry( message )
    local entry = {
        message = message,
        time = getRealTime()
    };

    table.insert( logEntries, entry );
end

-- Event handler to add log entries when chat messages are created.
addEventHandler( "onClientChatMessage", root,
    function(message)
        -- Forward the message into our logging system.
        addLogEntry( message );
    end
);
    

-- Write the log when the resource is terminated.
addEventHandler( "onClientResourceStop", root,
    function()
        -- todo: write session start and end times.

        -- Write the amount of log entries.
        logFile.writeShort( #logEntries );

        -- Write the log entries.
        for m,n in ipairs( logEntries ) do
            local encryptedMessage = teaEncode( n.message );

            logFile.writeShort( #encryptedMessage );
            logFile.write( encryptedMessage );

            -- Write date information.
            logFile.writeShort( n.time.second ); logFile.writeShort( n.time.minute ); logFile.writeShort( n.time.hour );
            logFile.writeShort( n.time.monthday ); logFile.writeShort( n.time.month + 1 ); logFile.writeShort( n.time.year + 1900 );
        end
    end
);

-- todo: create a log file viewer.

FileSystem File Functions