appendfile

appendfile

function appendfile( path, data [, prefix [, suffix]] ) --> res, err

Description

This function will append some data to the file at the specified path.

Parameters

path

Path to the file to modify.

data

Chunks of data to add at end of file. It can be a table of string or a single string (in case of single chunk).

prefix

Data to be written before each chunk of data.

suffix

Data to be written after each chunk of data.

Return Values

res

true or nil if an error occurse.

err

A message if an error occurse, otherwise nil.

Code

--ZFUNC-appendfile-v0
local function appendfile( path, data, prefix, suffix ) --> res, err

   local function writeorclose( f, data )
      local res, err = f:write( data )
      if err then f:close() end
      return res, err
   end

   local d, derr = io.open( path, "a+b" )
   if derr then
      return nil, "Can not create or open destination file. "..derr
   end

   local ok, err = d:seek( "end" )
   if err then
      d:close()
      return nil, err
   end

   if "string" == type( data ) then
      data = { data }
   end

   -- Output loop
   for i = 1, #data do

      if prefix then
         ok, err = writeorclose( d, prefix )
         if err then return ok, err end
      end

      ok, err = writeorclose( d, data[ i ] )
      if err then return ok, err end

      if suffix then
         ok, err = writeorclose( d, suffix )
         if err then return ok, err end
      end
   end

   return d:close()
end

return appendfile

Examples

local t = require "taptest"
local appendfile = require "appendfile"
local readfile = require "readfile"

t( appendfile( "appendfile.txt", "123" ), true )
t( readfile( "appendfile.txt" ), "123" )

t( appendfile( "appendfile.txt", "456" ), true )
t( readfile( "appendfile.txt" ), "123456" )

t( appendfile( "appendfile.txt", { "7","8" } ), true )
t( readfile( "appendfile.txt" ), "12345678" )

t( appendfile( "appendfile.txt", {"9","10"}, "<", ">" ), true )
t( readfile( "appendfile.txt" ), "12345678<9><10>" )

os.remove( "appendfile.txt" )

t()

See also