MTA:Eir/FileSystem/file/readShort
Jump to navigation
Jump to search
This function attempts to read a short (native type) from a file and returns it. The amount of bytes read should be two.
Syntax
short file:readShort ()
Returns
Returns the short integer if it was successfully read from the file, false otherwise.
Example
Click to collapse [-]
ClientThis snippet reads and writes string buffers into a custom file format.
local function writeBuffers( outFile, buffers ) -- Write header information. outFile:writeInt( #buffers ); -- number of buffers -- Write the buffers. for m,n in ipairs( buffers ) do local bufferContent = tostring( n ); -- Write header of buffer. outFile:writeShort( #bufferContent ); -- length of buffer -- Write the content outFile:write( bufferContent ); end end local function readBuffers( inFile ) local buffers = {}; -- Read header information. local numBuffers = inFile:readInt(); -- Make sure we read the int correctly. -- Fails if the file has less than 4 bytes to read. if ( numBuffers ) then local n = 1; while ( n <= numBuffers ) do -- Read buffer header. local bufferSize = inFile:readShort(); -- We always have to add the amount of buffers specified by the header. -- Hence we always add a buffer to the result array. local buffer = ""; if ( bufferSize ) then -- Read the buffer. buffer = inFile:read( bufferSize ); end -- Append the result buffer. buffers[n] = buffer; n = n + 1; end end return buffers; end -- Manager some buffers in a file. local myBuffers = { "Hello World!", "Cooking eggs on a frying pan", "The American Pizzas taste awesome", "There is no bathroom." }; local theFile = fileCreate( "buffers.dat" ); -- First write the buffers into the file. writeBuffers( theFile, myBuffers ); -- Now retrieve them again. theFile:seek( 0, "set" ); myBuffers = readBuffers( theFile ); -- Output the buffers. for m,n in ipairs( myBuffers ) do outputChatBox( n ); end