Module fs
Filesystem access.
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.
- 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.
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.
- 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 {}
- file_exists(path)
-
Checks for a file’s existence.
Returns true if the file (which may be a directory) exists, or a triad otherwise.
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
- 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.
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.
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
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).
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.
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.
- 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).
- opendir(path)
-
Opens a directory for reading.
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
- 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.
- 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.
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.
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.
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))
- 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.
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.