Module fs

Filesystem access.

Unless otherwise noted, most functions here return a triad on error. By wrapping calls to such functions in assert you achieve the “throw exceptions on errors” programming style.

See also the higher-level file operations in the mc module.

Functions

StatBuf(t) Constructs a fs.StatBuf object.
VPath(path[, relative]) Constructs a fs.VPath object.
_vfs_expire([force]) Releases virtual filesystems not in use.
chdir(path) Changes the current directory.
chmod(path, mode) Changes a file’s permission bits.
chown(owner, group) Changes a file’s ownership.
current_dir() Returns the current directory, as a string.
current_vdir() Returns the current directory, as a fs.VPath.
dir(path) Returns a directory’s contents.
file_exists(path) Checks for a file’s existence.
files(path) Iterates over files in a directory.
fnmatch(pattern, filename[, opts]) Matches a file against shell pattern.
getlocalcopy(path) Creates a local copy of a file.
glob(pattern[, opts]) Globbing.
lines(filename[, what]) Iterates over a file’s lines.
link(oldpath, newpath) Creates a hard-link.
lstat(path[, ...]) Returns a file’s properties.
mkdir(path[, perm]) Creates a directory.
mknod(path, mode, dev) Creates a special (or ordinary) file
nonvfs_access(path, mode) Checks access permission for a file.
nonvfs_mkdir_p(path[, perm]) Creates a directory and its parents.
nonvfs_realpath(path) Returns the absolute canonical form of a path.
open(filepath, [mode], [perm]) Opens a file.
opendir(path) Opens a directory for reading.
read(filename[, length[, offset]]) Reads an entire file.
readlink(path) Reads a symbolic link.
register_filesystem(spec) Registers a filesystem.
rename(oldpath, newpath) Renames a file.
rmdir(path) Removes a directory.
stat(path[, ...]) Returns a file’s properties.
strerror(errorcode) Converts an error code to a human-readable string.
symlink(oldpath, newpath) Creates a symbolic link.
temporary_file([opts]) Creates a temporary file.
temporary_string_file(...) Creates a temporary file with certain content.
tglob(pattern[, opts]) Globbing, into a table.
ungetlocalcopy(path, local_path, has_changed) Ungets a local copy.
unlink(path) Deletes a file.
utime(path[, modification_time[, last_access_time]]) Sets a file’s timestamps.
write(filename, ...) Writes an entire file.


Functions

StatBuf(t)
Constructs a fs.StatBuf object.

Given a table with fields like “size”, “type” etc., this function constructs the corresponding fs.StatBuf object. For missing fields sane defaults will be picked.

End-users won’t ever need to use this function. In the one case where end-users do need to conjure up a StatBuf they can use a table instead.

VPath(path[, relative])
Constructs a fs.VPath object.

If path is already a VPath object, it’s returned as-is.

_vfs_expire([force])
Releases virtual filesystems not in use.

You shouldn’t need to use this in normal code. This is done automatically by MC (see core/_bootstrap.lua).

By default only filesystems not used for at least a certain amount of time (typically 60 seconds) are released. By using the force flag you direct MC to release any filesystem not in use.

chdir(path)
Changes the current directory.

MC knows about 3 directories: the left panel’s, the right panel’s, and the current directory. The latter is transient: it usually gets reset to one of the panel’s while the user works with them. If you want the directory change to have a more permanent nature, change the panel's direcory instead of using fs.chdir().

chmod(path, mode)

Changes a file’s permission bits.

fs.chmod("/path/to/file", tonumber("666", 8))
chown(owner, group)
Changes a file’s ownership.

Parameters:

  • owner id. Leave empty (or -1) to not change this ID.
  • group id. Leave empty (or -1) to not change this ID.
current_dir()
Returns the current directory, as a string.
current_vdir()
Returns the current directory, as a fs.VPath.
dir(path)
Returns a directory’s contents.

Returns a list of all the files in a directory. On error, returns a triad.

local files = fs.dir("/home/mooffie") or {}

See also files, glob.

file_exists(path)
Checks for a file’s existence.

Returns true if the file (which may be a directory) exists, or a triad otherwise.

This is simply a wrapper that calls nonvfs_access. The benefit of using it is its self-documenting name.

Parameters:

  • path The pathname.
files(path)
Iterates over files in a directory.

Raises an error if the directory could not be read (e.g., doesn’t exist or no read permission).

for file in fs.files("/home/mooffie")
  print(file)
end

See also dir, glob, opendir.

fnmatch(pattern, filename[, opts])
Matches a file against shell pattern.

Returns true if a filename matches a shell pattern. The file does not need to exist.

if fnmatch("*.{gif,jp{e,}g}", filename) do
  alert("It's an image!")
end

The optional opts argument is described in glob (only nocase and utf8 are relevant).

getlocalcopy(path)
Creates a local copy of a file.

If the file isn’t on the local file system, this function creates a copy of it, in some temporary directory, and returns the path for this copy.

If the file is already on the local file system, this function returns the path as-is.

This functions is needed when you want to execute an operating system command on some arbitrary file. Since the file can reside on some non-local file system, you can’t use its path directly. E.g., you can’t do the following:

os.execute("wc -l ./archive.tgz/tar://file.txt")

Instead, you first call getlocalcopy to create a local copy of the file:

local lcl_path = fs.getlocalcopy("./archive.tgz/tar://file.txt")
os.execute("wc -l " .. lcl_path)
fs.ungetlocalcopy("./archive.tgz/tar://file.txt", lcl_path, false)

You should also call ungetlocalcopy to cleanup after yourself, as demonstrated here.

glob(pattern[, opts])
Globbing.

Iterates over all files matching a shell pattern. Returns the file paths.

for file in glob('/home/mooffie/Documents/**/*.txt') do
  print(file)
end

The files aren’t sorted: the block is executed as each file is found.

Options

The optional opts table holds various customization options and flags.

  • opts.nocase – If true, ignores case when matching filenames. “*.c” would match both “file.c” and “file.C”.
  • opts.utf8 — If true, filenames are assumed to be UTF-8 encoded (“?” matches a character, not byte, and ops.nocase works). If false, this handling is turned off. If missing (nil), decision is based on tty.is_utf8 (as MC itself does).
  • opts.fail – If true, an exception is raised in case of error (e.g., directory with no read permission, etc.); otherwise, errors are silently ignored.
  • opts.conditions – a list of functions to filter the results by. Each function (“predicate”) gets the following arguments: the full path, a fs.StatBuf, and the basename. It should return true if the file is to be included in the results. A file has to satisfy all the conditions.
  • opts.stat – If true, returns a fs.StatBuf in addition to the file path.
  • opts.type – Limits the results to files of a certain type.

Both glob("*", {type="directory"}) and glob("*/") are ways to limit results to directories only, but the latter appends a slash to each name.

Patterns

The usual shell patterns are recognized. Curly brackets denote alternatives. “**” descends into subfolders. In contrast to the shell, “*does match dot at start of filename (if you want to eliminate such files, use ops.conditions, as demonstrated below).

-- Get rid of files beginning with dot.
local function nodot(_,_,base)
  return not base:find '^%.'
end

-- Note the 'nocase': we want "img.GIF" to match too.
for f in fs.glob("*.{gif,jp{e,}g}", {conditions={nodot}, nocase=true}) do
  ...
end

It may not be safe to delete files while traversing with glob (as it’s essentially a readdir(3) loop). Use tglob instead.

See also tglob.

lines(filename[, what])
Iterates over a file’s lines.

This is like Lua’s built-in io.lines, but it supports the Virtual File System.

link(oldpath, newpath)
Creates a hard-link.
lstat(path[, ...])
Returns a file’s properties.

Symbolic links aren’t resolved.

Returns a fs.StatBuf object. On error, returns a triad.

See also stat for further details.

mkdir(path[, perm])
Creates a directory.

Parameters:

  • path
  • perm Optional. The permission with which to create the new directory. Defaults to 0777. This will be clipped by the umask. (optional)
mknod(path, mode, dev)
Creates a special (or ordinary) file
nonvfs_access(path, mode)
Checks access permission for a file.

This function is an interface to the system’s access(2). See its manual page. It checks the read/write/execute permission bits, or existence, of a file (or directory).

Since this function is the kernel’s, it doesn’t know of MC’s VFS. So it won’t work for files in archives, sh://, etc. The prefix “nonvfs_” is there to remind you of this.

If you do pass it a non local VFS path, it will work by calling stat. I.e., it will check for path existence only, ignoring permission bits.

The function returns true if access is granted, or a triad otherwise.

Parameters:

  • path The pathname.
  • mode One of “r”, “w”, “x”, “” (the empty string checks existence, not permission).
nonvfs_mkdir_p(path[, perm])
Creates a directory and its parents.

This is an interface to a function in MC’s core which does not support the VFS. So it won’t work for nested directories in archives, sh://, etc. The prefix “nonvfs_” is there to remind you of this.

This will be fixed in the future.

Parameters:

  • path
  • perm Optional. The permission with which to create the new directory and its parents. Defaults to 0777. This will be clipped by the umask. (optional)
nonvfs_realpath(path)
Returns the absolute canonical form of a path. All symbolic links are resolved.

This only works for paths in the local file system (the prefix “nonvfs_” is there to remind you of this), and the path has to point to a file that exists. If these two conditions aren’t met, nil is returned.

If all you want is to resolve “/./”, “/../”, and excessive “/"s, and the file may not actually exist, use VPath instead.

open(filepath, [mode], [perm])
Opens a file.

Returns a fs.File object on success, or a triad on error.

You should use this function instead of io.open because the latter doesn’t support the Virtual File System. Some extensions this function introduces:

mode is either a symbolic symbolic mode name (like “r”, “w+”, etc.) or a numeric code (like utils.bit32.bor(fs.O_RDWR, fs.O_APPEND)).

perm is the permission with which to create new files. Defaults to 0666 (which will be further clipped by the umask).

When opening a file for both input and output, you must intervene between :read() and :write() operations by :seek() or :flush(). This concurs with the C standard as well.

(This issue pertains to buffered IO only. When doing unbuffered IO (using :sysread() and :syswrite()) this issue doesn’t exist.)

opendir(path)
Opens a directory for reading.

This is a relatively low-level function. It’s easier to just use files.

On success, returns a “directory handle” object that has two methods:

  • next(), which returns a file name and inode number (or nil when it arrives at the end).

  • close(), which may be used to prematurely close the directory. It gets automatically called for you when a :next() returns nil or when the object gets garbage collected.

On error, returns a triad.

local dirh, error_message = fs.opendir("/home/mooffie")
if not dirh then
  print("Sorry, I can't show you your files. Error: " .. error_message)
else
  print("The first 10 files:")
  for i = 1, 10 do
    print(dirh:next())
  end
  dirh:close()
end

-- A much shorter variation of the above:
local dirh = assert(fs.opendir("/home/mooffie"))
for file in dirh.next, dirh do
  print(file)
end

See also files, dir, glob.

read(filename[, length[, offset]])
Reads an entire file.

This is a simple utility function.

The optional length argument lets you read only a portion of the file. This argument is passed down to fs.File:read and defaults to "*a".

The optional offset argument lets you seek in the file before reading. A negative offset means seeking from the end of the file.

Returns:

The function returns the string read, or a triad on error.

Wrap the function call in assert if you want to raise an exception on error.

readlink(path)
Reads a symbolic link.
register_filesystem(spec)
Registers a filesystem.

See the user guide for a detailed explanation.

rename(oldpath, newpath)
Renames a file.

See also the high-level mc.mv, which can move files across devices.

rmdir(path)
Removes a directory.

The directory has to be empty. If it isn’t your case, use the high level mc.rm instead.

stat(path[, ...])
Returns a file’s properties.

Returns a fs.StatBuf object. On error, returns a triad.

See also lstat.

If you're interested in a couple of fields only, you can fetch them immediately by specifying their names:

if fs.stat("/path/to/file", "type") == "directory" then
  alert("This is a directory")
end

…which is more efficient (and shorter) than doing:

if (fs.stat("/path/to/file") or {}).type == "directory" then
  alert("This is a directory")
end
-- We added 'or {}' to make it functionally equivalent to
-- the previous code: for the case when stat() fails.

Parameters:

  • path
  • ... Either none, to return a whole fs.StatBuf, or names of fields to return.
strerror(errorcode)
Converts an error code to a human-readable string.

You shouldn’t need to use this function. There’s not much reason to keep error codes around. The most straightforward way to handle errors is to simply wrap the call to the desired I/O function in assert or abort.

If you do want to show error messages yourself, then instead use the 2'nd element of the error triad, as it also includes the the pathname involved (something strerror can’t tell you).

Parameters:

  • errorcode A numeric code previously returned as the 3'rd element of a triad.
symlink(oldpath, newpath)
Creates a symbolic link.
temporary_file([opts])

Creates a temporary file.

Unless otherwise instructed, returns two values: a file object, and a pathname

The file is created with the permission 0600, meaning that only the owner will have access to its contents.

If the file could not be created (e.g., on a read-only filesystem), raises an exception.

The optional opts may contain the following fields:

  • name_only: Boolean. Return only the pathname; do not open the file.
  • delete: Boolean. Delete the file immediacy; return only the file object.
  • prefix: A string to appear at the beginning of the basename; defaults to “lua”.
  • suffix: A string to appear at the end of the basename
temporary_string_file(...)
Creates a temporary file with certain content.

Writes a string (or strings) to a temporary file and returns the path to this file.

This is simply an easy-to-use wrapper around temporary_file.

In case of error, raises an exception.

Example:

local temp = fs.temporary_string_file(
  "[client]\n",
  "user=" .. user .. "\n",
  "password=" .. password .. "\n"
)
os.execute("mysqldump --defaults-extra-file=" .. temp .. " mydb tbl1")
assert(fs.unlink(temp))

This:

fs.temporary_string_file(huge_string, "\n")

… is more efficient than this:

fs.temporary_string_file(huge_string .. "\n")

(This tip applies to file:write too.)

tglob(pattern[, opts])
Globbing, into a table.

Like glob, but it isn’t an iterator: the matching files are returned as a table.

The table returned is sorted.

local files = tglob('/home/mooffie/*.txt')

See glob for the description of the arguments. In addition to the options mentioned there, tglob() supports nosort, which disables the sorting of the files.

ungetlocalcopy(path, local_path, has_changed)
Ungets a local copy.

Deletes the local copy obtained by getlocalcopy. If this copy has changed (as per the flag), the local copy is first copied onto the original file.

If the original file is already on the local file system, this function is a no-op.

See example at getlocalcopy.

Parameters:

  • path The original file
  • local_path The local copy
  • has_changed Boolean. Has the file changed?
unlink(path)
Deletes a file.

See also the high-level mc.rm.

utime(path[, modification_time[, last_access_time]])
Sets a file’s timestamps.

Parameters:

  • path
  • modification_time Timestamp. Defaults to now. (optional)
  • last_access_time Timestamp. Defaults to now. (optional)
write(filename, ...)
Writes an entire file.

This is a simple utility function that lets you create a file with certain content in just one line of code:

Instead of the following proper code:

local f = assert(fs.open('file.txt', 'w'))
assert(f:write('output string'))
assert(f:close())

…you can write:

assert(fs.write('file.txt', 'output string'))

Returns:

The function returns true on sucess, or a triad on error.

You'd most certainly want to wrap the function call in assert, to raise an exception on error.

generated by LDoc 1.4.3 Last updated 2016-08-23 17:29:40