File Input Output

lua-users home
wiki

The following code contains a few utility file input/output functions. These raise an error if they fail. They can also be useful for writing command-line utilities and small scripts, as the error raising (rather than returning nil) avoids silently continuing on failure.

-- Find the length of a file
--   filename: file name
-- returns
--   len: length of file
--   asserts on error
function length_of_file(filename)
  local fh = assert(io.open(filename, "rb"))
  local len = assert(fh:seek("end"))
  fh:close()
  return len
end

-- Return true if file exists and is readable.
function file_exists(path)
  local file = io.open(path, "rb")
  if file then file:close() end
  return file ~= nil
end

-- Guarded seek.
-- Same as file:seek except throws string
-- on error.
-- Requires Lua 5.1.
function seek(fh, ...)
  assert(fh:seek(...))
end

-- Read an entire file.
-- Use "a" in Lua 5.3; "*a" in Lua 5.1 and 5.2
function readall(filename)
  local fh = assert(io.open(filename, "rb"))
  local contents = assert(fh:read(_VERSION <= "Lua 5.2" and "*a" or "a"))
  fh:close()
  return contents
end

-- Write a string to a file.
function write(filename, contents)
  local fh = assert(io.open(filename, "wb"))
  fh:write(contents)
  fh:flush()
  fh:close()
end

-- Read, process file contents, write.
function modify(filename, modify_func)
  local contents = readall(filename)
  contents = modify_func(contents)
  write(filename, contents)
end

Old Lua 4 Stuff

The following examples are from Lua 4, included here only for historical reasons.

-- Guarded readfrom (Lua4)
--   [f]: file name
-- Note: In Lua5 use io.input().
function readfrom(f)
  local h, err
  if f then h, err = %readfrom(f)
  else      h, err = %readfrom()
  end
  affirm(h, "can't read from " .. (f or "stdin") .. ": " ..
         (err or ""))
  return h
end

-- Guarded writeto (Lua4)
--   [f]: file name
-- Note: In Lua5 use io.output().
function writeto(f)
  local h, err
  if f then h, err = %writeto(f)
  else      h, err = %writeto()
  end
  affirm(h, "can't write to " .. (f or "stdout") .. ": " ..
         (err or ""))
  return h
end

-- Guarded dofile (Lua4)
--   [f]: file name
-- Note: In Lua5, dofile throws on error.
function dofile(f)
  affirm(%dofile(f), "error while executing " .. f)
end

-- Guarded seek (Lua4)
--   f: file handle
--   w: whence to seek
--   o: offset
function seek(f, w, o)
  local ok, err
  if     o then ok, err = %seek(f, w, o)
  elseif w then ok, err = %seek(f, w)
  else          ok, err = %seek(f)
  end
  affirm(ok, "can't seek on " .. f .. ": " .. (err or ""))
end


-- Find the length of a file (Lua4)
--   f: file name
-- returns
--   len: length of file
function length_of_file(f)
  local h, len
  h = openfile(f, "r")
  len = seek(h, "end")
  closefile(h)
  return len
end

--JayCarlson - original (Lua 4 version)

See Also


RecentChanges · preferences
edit · history
Last edited May 14, 2020 8:21 am GMT (diff)