Home Contents | # Directory traversal | OS | Core4 Lua Commands

## SYNOPSIS

1. dir = os.opendir(path[, flags | nil[, name_filters]])
2. filename[, info] = dir:next()
3. for filename[, info] in dir:files() ...
4. dir:close()

## DESCRIPTION

This group of functions allow reading the contents of a directory.

To scan a directory, open a directory handle first by calling os.opendir(). The parameter path selects the directory.

Each character in the string flags modifies the behaviour of the directory scan:

- 'I': Traversal functions return a second value, a table containing the result of the rawio.stat() call.
  As this is expensive, it is not active by default.
- 'D': List directories
- 'F': List normal files
- 'S': List special files
- 'L': List symbolic links
- '.': Also list the special entries "." and ".."
- 'c': Filter is not case sensitive
- 'P': Return full path for each entry, not just the filename.

If neither 'D', 'F', 'S' nor 'L' is given, defaults to "DFSL".

name_filters can be a string or a list containing common wildcard filters (e.g. "*.txt")

After obtaining a handle, calling dir:next() returns one directory entry on each call, until the directory has been completely read. Then it returns nil.

Alternatively, using dir:files() can be used with a generic for-loop.

When done, it is good style to close the handle with dir:close(). Close happens automatically on garbage collection, but that takes an unknown amount of time, at which you might have already run out of file descriptors.

## RETURN VALUE

os.opendir() returns a directory handle on success. On error, three values are returned: nil, a string describing the error (The result of the C library call strerror() on the errno code) and the errno number from the standard C library.

## EXAMPLE

> > > >
dir = os.opendir("/media") for file in dir:files() do print(file) end

## SEE ALSO

os.chdir, os.cwd, os.mkdir, os.remove, os.scandir