Programming Search⌘K

Taskcore

List files in a directory

Also called list a directory, walk a directory tree, read the entries of a folder, recursive directory listing.

List the entries of one directory or of a whole tree in a fixed sorted order, list symbolic links without following them, and report an error for a missing directory.

Task

List the entries of a directory. With the recursive option, list the entries of the whole tree under it.

Each entry is a path relative to the directory, with / between the parts. A directory has a / at the end, so the reader can see the type. The list does not hold . and ... It holds names that start with ., because they are entries too.

The list is in ascending order of Unicode code points. The file system gives the entries in an order of its own, which can change between machines and file systems. A program that prints the raw order is not repeatable, so the solution sorts. The sort is on the whole relative path. So a.txt comes before a/ and a/x, because . (U+002E) is less than / (U+002F). The order does not depend on the locale, so B.txt comes before a.txt.

A symbolic link is an entry, and it is listed by its own name with no /. The solution never follows a link, also when the link points to a directory. This gives the same result for a broken link, and a link that points to its own parent cannot make the walk loop.

If the path does not exist, or it names a file and not a directory, the solution reports an error and returns no list.

The tests make each tree in a new temporary directory, so the result is the same on each machine. The node has no fixtures.

Solutions

Each solution reads one directory at a time, asks the type of each entry without following links, and recurses into the real directories only. Then it sorts the whole list once.

  • Python. os.scandir gives DirEntry objects in arbitrary order. entry.is_dir(follow_symlinks=False) is false for a link. The default follow_symlinks=True is true for a link to a directory.
  • JavaScript and TypeScript (Node.js). readdir from node:fs/promises with withFileTypes: true gives Dirent objects. isDirectory() is false for a link and isSymbolicLink() is true, so the recursion stops at links. The default sort() compares UTF-16 code units. That is code point order for names in the Basic Multilingual Plane.
  • Java. Files.walk(root, depth) does not follow links unless it gets FOLLOW_LINKS. Depth 1 lists one directory. The stream starts with the root itself, so the code skips it. Files.walk on a file returns the file, so the code checks the type of the root first and throws NotDirectoryException.
  • C#. DirectoryInfo.EnumerateFileSystemInfos with an EnumerationOptions object lists one directory, and the code recurses itself. RecurseSubdirectories = true follows a link to a directory, as the pitfall below shows. Set AttributesToSkip = 0 and IgnoreInaccessible = false, because the defaults skip hidden entries and hide errors. LinkTarget is not null for a link. A path that names a file gives DirectoryNotFoundException, so the code checks File.Exists first. Sort with StringComparer.Ordinal.
  • Go. os.ReadDir returns the entries of one directory sorted by file name. IsDir is false for a link. The code still sorts at the end, because the order of each directory is not the order of the whole list.
  • Rust. fs::read_dir gives the entries in an order that depends on the platform. DirEntry::file_type does not follow links. The code returns an error of kind InvalidData for a name that is not UTF-8, and NotADirectory comes from read_dir.
  • C. POSIX opendir and readdir in a loop, with errno set to 0 before each call to tell the end from an error. readdir returns . and .., so the code skips them. fstatat with AT_SYMLINK_NOFOLLOW gives the type of the link itself. qsort with strcmp sorts by byte, and for UTF-8 that is code point order.
  • C++. std::filesystem::recursive_directory_iterator does not follow links by default. directory_iterator lists one directory. Both skip . and .., and the order is unspecified. directory_entry::is_directory follows a link, so the code tests is_symlink first.
  • Bash (4.4 or later). A loop over "$dir"/* in a subshell with shopt -s dotglob nullglob, so the options do not leak. [[ -d $p && ! -L $p ]] finds a real directory, because -d follows a link. LC_ALL=C sort sorts by byte. A name with a newline would break the output, so the contract excludes it.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the tree as a list: a name that ends in / is a directory, and link -> target is a symbolic link. The cases that must give an error are in cases/errors.jsonl.

  • empty and empty-subdir: an empty directory gives an empty list. In Bash without nullglob, the pattern * stays as the literal word *.
  • hidden: .env and .git/ are in the list. Bash globs and C# with a new EnumerationOptions skip them by default.
  • case-order: B.txt comes before a.txt in code point order. Bash globs sort by the collation order of the locale (LC_COLLATE), so their order changes with the locale.
  • dot-before-slash: the list is a-b, a.txt, a/, a/x. A walk that prints each directory in order gives a/, a/x, a.txt, so the sort must be on the whole path.
  • symlink-to-dir: link points to real/. It is listed once, with no /, and its contents are not listed again. C# with RecurseSubdirectories lists them again.
  • symlink-to-file and broken-symlink: a link is listed also when its target is a file or does not exist. A check that follows links fails on the broken link.
  • symlink-loop: d/up points to ... A walk that follows links never ends, or stops with an error.
  • spaces and non-ascii: été.txt comes after zebra.txt, because é is U+00E9.
  • Errors: a path that does not exist, and a path that names a file.

Pitfalls

  • Bash globs skip dot files and keep a pattern that matches nothing. Without dotglob, * does not match .env. Without nullglob, an empty directory gives the word empty/*:

This code runs but gives a wrong answer on purpose.

mkdir -p tree/empty && touch tree/.env tree/main.go
for p in tree/*; do echo "entry: $p"; done
for p in tree/empty/*; do echo "entry: $p"; done
Output
entry: tree/empty
entry: tree/main.go
entry: tree/empty/*

Set both options:

mkdir -p tree/empty && touch tree/.env tree/main.go
shopt -s dotglob nullglob
for p in tree/*; do echo "entry: $p"; done
for p in tree/empty/*; do echo "entry: $p"; done
Output
entry: tree/.env
entry: tree/empty
entry: tree/main.go
  • The type check follows the link. In C++, directory_entry::is_directory reports the type of the target. Python DirEntry.is_dir() does the same by default, and os.walk puts a link to a directory in its list of directory names:
#include <filesystem>
#include <print>

namespace fs = std::filesystem;

int main() {
    fs::create_directories("tree/real");
    fs::create_directory_symlink("real", "tree/link");
    fs::directory_entry link{"tree/link"};
    std::println("is_directory: {}", link.is_directory());
    std::println("is_symlink: {}", link.is_symlink());
}
Output
is_directory: true
is_symlink: true
import os

os.makedirs("tree/real", exist_ok=True)
os.symlink("real", "tree/link")
root, dirnames, filenames = next(os.walk("tree"))
print("dirnames:", sorted(dirnames))
link = next(e for e in os.scandir("tree") if e.name == "link")
print("is_dir():", link.is_dir())
print("is_dir(follow_symlinks=False):", link.is_dir(follow_symlinks=False))
Output
dirnames: ['link', 'real']
is_dir(): True
is_dir(follow_symlinks=False): False
  • A new EnumerationOptions in C# skips hidden entries, and its recursion follows links. Its AttributesToSkip is Hidden | System by default. On Unix, .NET marks a name that starts with . as Hidden. With RecurseSubdirectories = true, the output also holds tree/link/f, so the files under real are listed twice:

This code runs but gives a wrong answer on purpose.

Directory.CreateDirectory("tree/real");
File.WriteAllText("tree/real/f", "");
File.WriteAllText("tree/.env", "");
File.CreateSymbolicLink("tree/link", "real");
var options = new EnumerationOptions { RecurseSubdirectories = true };
foreach (string path in Directory.GetFileSystemEntries("tree", "*", options).Order(StringComparer.Ordinal))
{
    Console.WriteLine(path);
}
Output
tree/link
tree/link/f
tree/real
tree/real/f
  • Following links can loop. Java Files.walk with FOLLOW_LINKS detects a link to an ancestor and throws FileSystemLoopException, wrapped in an UncheckedIOException. Do not follow links unless the task needs it:
import java.io.UncheckedIOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) throws Exception {
    Path d = Files.createDirectories(Path.of("tree/d"));
    Files.createSymbolicLink(d.resolve("up"), Path.of(".."));
    try (var paths = Files.walk(Path.of("tree"), FileVisitOption.FOLLOW_LINKS)) {
      paths.forEach(p -> {});
    } catch (UncheckedIOException e) {
      System.out.println(e.getCause().getClass().getSimpleName());
    }
    try (var paths = Files.walk(Path.of("tree"))) {
      System.out.println(paths.count() + " paths without FOLLOW_LINKS");
    }
  }
}
Output
FileSystemLoopException
3 paths without FOLLOW_LINKS
  • The raw order of the file system. Python os.listdir and os.scandir, Rust read_dir, Go File.ReadDir and the C++ iterators give no fixed order. A test that compares the raw order can pass on one machine and fail on another. Sort before you print or compare.

Code

The build runs the native tests of each language in a pinned toolchain.

list_entries.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/list-files-in-a-directory/.

import os


def list_entries(root: str | os.PathLike[str], recursive: bool) -> list[str]:
    """Return the relative paths of the entries under root, sorted by code point.

    A directory has a "/" at the end. A symbolic link is listed, but it is
    never followed.
    """
    out: list[str] = []

    def walk(directory: str | os.PathLike[str], prefix: str) -> None:
        with os.scandir(directory) as entries:
            for entry in entries:
                if entry.is_dir(follow_symlinks=False):
                    out.append(prefix + entry.name + "/")
                    if recursive:
                        walk(entry.path, prefix + entry.name + "/")
                else:
                    out.append(prefix + entry.name)

    walk(root, "")
    out.sort()
    return out
test_list_entries.py 58 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/list-files-in-a-directory/.

import os
from pathlib import Path

import pytest

from list_entries import list_entries

TREE = ["docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"]

CASES = {
    "flat": (["b.txt", "a.txt", "c.txt"], False, ["a.txt", "b.txt", "c.txt"]),
    "nested": (TREE, True, TREE),
    "nested-shallow": (TREE, False, ["docs/", "readme.md"]),
    "empty": ([], True, []),
    "empty-subdir": (["empty/"], True, ["empty/"]),
    "hidden": ([".env", ".git/", ".git/config", "main.go"], True, [".env", ".git/", ".git/config", "main.go"]),
    "case-order": (["a.txt", "B.txt", "c.txt"], False, ["B.txt", "a.txt", "c.txt"]),
    "dot-before-slash": (["a/", "a/x", "a.txt", "a-b"], True, ["a-b", "a.txt", "a/", "a/x"]),
    "symlink-to-dir": (["real/", "real/f", "link -> real"], True, ["link", "real/", "real/f"]),
    "symlink-to-file": (["f", "g -> f"], True, ["f", "g"]),
    "broken-symlink": (["dangling -> nowhere"], True, ["dangling"]),
    "symlink-loop": (["d/", "d/up -> .."], True, ["d/", "d/up"]),
    "spaces": (["my file.txt", "two  spaces/", "two  spaces/x"], True, ["my file.txt", "two  spaces/", "two  spaces/x"]),
    "non-ascii": (["été.txt", "zebra.txt", "apple.txt"], False, ["apple.txt", "zebra.txt", "été.txt"]),
}


def make_tree(root: Path, tree: list[str]) -> None:
    """Make each entry of the tree under root, in order."""
    for entry in tree:
        if " -> " in entry:
            name, target = entry.split(" -> ")
            os.symlink(target, root / name)
        elif entry.endswith("/"):
            (root / entry).mkdir()
        else:
            (root / entry).touch()


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    tree, recursive, want = CASES[name]
    make_tree(tmp_path, tree)
    assert list_entries(tmp_path, recursive) == want


def test_missing(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        list_entries(tmp_path / "missing", True)


def test_not_a_directory(tmp_path: Path) -> None:
    make_tree(tmp_path, ["notes.txt"])
    with pytest.raises(NotADirectoryError):
        list_entries(tmp_path / "notes.txt", True)
list_entries.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

#include "list_entries.hpp"

#include <algorithm>
#include <utility>

namespace fs = std::filesystem;

namespace {

void add(const fs::path& root, const fs::directory_entry& entry, std::vector<std::string>& out) {
    std::string rel = entry.path().lexically_relative(root).generic_string();
    // is_directory follows a symbolic link, so test is_symlink first.
    if (!entry.is_symlink() && entry.is_directory()) rel += '/';
    out.push_back(std::move(rel));
}

}  // namespace

std::vector<std::string> list_entries(const fs::path& root, bool recursive) {
    std::vector<std::string> out;
    if (recursive) {
        // The default options do not follow a symbolic link to a directory.
        for (const auto& entry : fs::recursive_directory_iterator(root)) add(root, entry, out);
    } else {
        for (const auto& entry : fs::directory_iterator(root)) add(root, entry, out);
    }
    // The iteration order is unspecified. std::string compares the bytes as
    // unsigned char, and for UTF-8 that is code point order.
    std::ranges::sort(out);
    return out;
}
list_entries.hpp 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

#ifndef LIST_ENTRIES_HPP
#define LIST_ENTRIES_HPP

#include <filesystem>
#include <string>
#include <vector>

// list_entries returns the relative paths of the entries under root, sorted by
// byte. A directory has a "/" at the end. A symbolic link is listed, but it is
// never followed. It throws std::filesystem::filesystem_error on an error, with
// the code no_such_file_or_directory or not_a_directory for a bad root.
std::vector<std::string> list_entries(const std::filesystem::path& root, bool recursive);

#endif
test_list_entries.cpp 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

#include <cstdio>
#include <fstream>
#include <string>
#include <system_error>
#include <vector>

#include "list_entries.hpp"

namespace fs = std::filesystem;

namespace {

const fs::path root = "list_entries_tree";

void make_tree(const std::vector<std::string>& tree) {
    fs::remove_all(root);
    fs::create_directory(root);
    for (const auto& entry : tree) {
        if (auto arrow = entry.find(" -> "); arrow != std::string::npos) {
            fs::create_symlink(entry.substr(arrow + 4), root / entry.substr(0, arrow));
        } else if (entry.ends_with('/')) {
            fs::create_directory(root / entry);
        } else {
            std::ofstream{root / entry};
        }
    }
}

int failures = 0;

void check(const std::string& name, bool ok) {
    if (!ok) {
        std::fprintf(stderr, "case %s failed\n", name.c_str());
        ++failures;
    }
}

std::errc code_of(const fs::path& path) {
    try {
        list_entries(path, true);
    } catch (const fs::filesystem_error& e) {
        return static_cast<std::errc>(e.code().value());
    }
    return {};
}

}  // namespace

int main() {
    struct Case {
        std::string name;
        std::vector<std::string> tree;
        bool recursive;
        std::vector<std::string> want;
    };
    const std::vector<std::string> tree = {"docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"};
    const std::vector<Case> cases = {
        {"flat", {"b.txt", "a.txt", "c.txt"}, false, {"a.txt", "b.txt", "c.txt"}},
        {"nested", tree, true, tree},
        {"nested-shallow", tree, false, {"docs/", "readme.md"}},
        {"empty", {}, true, {}},
        {"empty-subdir", {"empty/"}, true, {"empty/"}},
        {"hidden", {".env", ".git/", ".git/config", "main.go"}, true, {".env", ".git/", ".git/config", "main.go"}},
        {"case-order", {"a.txt", "B.txt", "c.txt"}, false, {"B.txt", "a.txt", "c.txt"}},
        {"dot-before-slash", {"a/", "a/x", "a.txt", "a-b"}, true, {"a-b", "a.txt", "a/", "a/x"}},
        {"symlink-to-dir", {"real/", "real/f", "link -> real"}, true, {"link", "real/", "real/f"}},
        {"symlink-to-file", {"f", "g -> f"}, true, {"f", "g"}},
        {"broken-symlink", {"dangling -> nowhere"}, true, {"dangling"}},
        {"symlink-loop", {"d/", "d/up -> .."}, true, {"d/", "d/up"}},
        {"spaces", {"my file.txt", "two  spaces/", "two  spaces/x"}, true, {"my file.txt", "two  spaces/", "two  spaces/x"}},
        {"non-ascii", {"été.txt", "zebra.txt", "apple.txt"}, false, {"apple.txt", "zebra.txt", "été.txt"}},
    };
    for (const auto& c : cases) {
        make_tree(c.tree);
        check(c.name, list_entries(root, c.recursive) == c.want);
    }

    make_tree({"notes.txt"});
    check("missing", code_of(root / "missing") == std::errc::no_such_file_or_directory);
    check("not-a-directory", code_of(root / "notes.txt") == std::errc::not_a_directory);
    fs::remove_all(root);
    return failures == 0 ? 0 : 1;
}
ListEntries.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/** Lists the entries of a directory, or of a whole tree. */
public final class ListEntries {
    private ListEntries() {}

    /**
     * Returns the relative paths of the entries under root, sorted by code point. A directory has
     * a "/" at the end. A symbolic link is listed, but it is never followed.
     *
     * @throws java.nio.file.NoSuchFileException if root does not exist
     * @throws NotDirectoryException if root is not a directory
     */
    public static List<String> list(Path root, boolean recursive) throws IOException {
        // Files.walk on a file gives the file itself, so check the type first.
        // readAttributes throws NoSuchFileException for a missing path.
        if (!Files.readAttributes(root, BasicFileAttributes.class).isDirectory()) {
            throw new NotDirectoryException(root.toString());
        }
        List<String> out = new ArrayList<>();
        // Files.walk does not follow symbolic links unless it gets FOLLOW_LINKS.
        try (Stream<Path> paths = Files.walk(root, recursive ? Integer.MAX_VALUE : 1)) {
            paths.skip(1).forEach(p -> {
                String rel = root.relativize(p).toString().replace(p.getFileSystem().getSeparator(), "/");
                out.add(Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS) ? rel + "/" : rel);
            });
        } catch (UncheckedIOException e) {
            throw e.getCause();
        }
        // String.compareTo compares UTF-16 code units. That is code point order
        // for names with no characters outside the Basic Multilingual Plane.
        out.sort(null);
        return out;
    }
}
ListEntriesTest.java 79 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class ListEntriesTest {
    @TempDir Path dir;

    static final List<String> TREE =
            List.of("docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md");

    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("flat", List.of("b.txt", "a.txt", "c.txt"), false, List.of("a.txt", "b.txt", "c.txt")),
                Arguments.of("nested", TREE, true, TREE),
                Arguments.of("nested-shallow", TREE, false, List.of("docs/", "readme.md")),
                Arguments.of("empty", List.of(), true, List.of()),
                Arguments.of("empty-subdir", List.of("empty/"), true, List.of("empty/")),
                Arguments.of("hidden", List.of(".env", ".git/", ".git/config", "main.go"), true,
                        List.of(".env", ".git/", ".git/config", "main.go")),
                Arguments.of("case-order", List.of("a.txt", "B.txt", "c.txt"), false, List.of("B.txt", "a.txt", "c.txt")),
                Arguments.of("dot-before-slash", List.of("a/", "a/x", "a.txt", "a-b"), true,
                        List.of("a-b", "a.txt", "a/", "a/x")),
                Arguments.of("symlink-to-dir", List.of("real/", "real/f", "link -> real"), true,
                        List.of("link", "real/", "real/f")),
                Arguments.of("symlink-to-file", List.of("f", "g -> f"), true, List.of("f", "g")),
                Arguments.of("broken-symlink", List.of("dangling -> nowhere"), true, List.of("dangling")),
                Arguments.of("symlink-loop", List.of("d/", "d/up -> .."), true, List.of("d/", "d/up")),
                Arguments.of("spaces", List.of("my file.txt", "two  spaces/", "two  spaces/x"), true,
                        List.of("my file.txt", "two  spaces/", "two  spaces/x")),
                Arguments.of("non-ascii", List.of("été.txt", "zebra.txt", "apple.txt"), false,
                        List.of("apple.txt", "zebra.txt", "été.txt")));
    }

    void makeTree(List<String> tree) throws IOException {
        for (String entry : tree) {
            int arrow = entry.indexOf(" -> ");
            if (arrow >= 0) {
                Files.createSymbolicLink(dir.resolve(entry.substring(0, arrow)), Path.of(entry.substring(arrow + 4)));
            } else if (entry.endsWith("/")) {
                Files.createDirectory(dir.resolve(entry));
            } else {
                Files.createFile(dir.resolve(entry));
            }
        }
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void lists(String name, List<String> tree, boolean recursive, List<String> want) throws IOException {
        makeTree(tree);
        assertEquals(want, ListEntries.list(dir, recursive), name);
    }

    @Test
    void missing() {
        assertThrows(NoSuchFileException.class, () -> ListEntries.list(dir.resolve("missing"), true));
    }

    @Test
    void notADirectory() throws IOException {
        makeTree(List.of("notes.txt"));
        assertThrows(NotDirectoryException.class, () -> ListEntries.list(dir.resolve("notes.txt"), true));
    }
}
list_entries.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

#define _POSIX_C_SOURCE 200809L

#include "list_entries.h"

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

struct list {
    char **items;
    size_t len, cap;
};

static int push(struct list *l, const char *prefix, const char *name, const char *suffix) {
    if (l->len == l->cap) {
        size_t cap = l->cap ? 2 * l->cap : 16;
        char **items = realloc(l->items, cap * sizeof *items);
        if (items == NULL) return -1;
        l->items = items;
        l->cap = cap;
    }
    size_t size = strlen(prefix) + strlen(name) + strlen(suffix) + 1;
    char *s = malloc(size);
    if (s == NULL) return -1;
    snprintf(s, size, "%s%s%s", prefix, name, suffix);
    l->items[l->len++] = s;
    return 0;
}

// walk adds the entries of the directory path to l. prefix is the relative
// path of the directory, with a "/" at the end, or "" for the root.
static int walk(const char *path, const char *prefix, bool recursive, struct list *l) {
    DIR *d = opendir(path);
    if (d == NULL) return -1;
    int rc = 0;
    for (;;) {
        errno = 0;
        struct dirent *e = readdir(d);
        if (e == NULL) {
            if (errno != 0) rc = -1;
            break;
        }
        // readdir also returns the entries "." and "..".
        if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue;
        // AT_SYMLINK_NOFOLLOW gives the type of a link, not of its target.
        struct stat st;
        if (fstatat(dirfd(d), e->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0) {
            rc = -1;
            break;
        }
        bool is_dir = S_ISDIR(st.st_mode);
        if (push(l, prefix, e->d_name, is_dir ? "/" : "") != 0) {
            rc = -1;
            break;
        }
        if (is_dir && recursive) {
            const char *rel = l->items[l->len - 1];
            size_t size = strlen(path) + strlen(e->d_name) + 2;
            char *sub = malloc(size);
            if (sub == NULL) {
                rc = -1;
                break;
            }
            snprintf(sub, size, "%s/%s", path, e->d_name);
            rc = walk(sub, rel, recursive, l);
            free(sub);
            if (rc != 0) break;
        }
    }
    int saved = errno;
    closedir(d);
    errno = saved;
    return rc;
}

static int compare(const void *a, const void *b) {
    // strcmp compares the bytes as unsigned char. For UTF-8 that is code point order.
    return strcmp(*(char *const *)a, *(char *const *)b);
}

int list_entries(const char *root, bool recursive, char ***out, size_t *n) {
    struct list l = {0};
    if (walk(root, "", recursive, &l) != 0) {
        int saved = errno;
        free_entries(l.items, l.len);
        errno = saved;
        return -1;
    }
    if (l.len > 0) qsort(l.items, l.len, sizeof *l.items, compare);
    *out = l.items;
    *n = l.len;
    return 0;
}

void free_entries(char **entries, size_t n) {
    for (size_t i = 0; i < n; i++) free(entries[i]);
    free(entries);
}
list_entries.h 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

#ifndef LIST_ENTRIES_H
#define LIST_ENTRIES_H

#include <stdbool.h>
#include <stddef.h>

// list_entries lists the entries under the directory root, and the whole tree
// if recursive is true. It stores in *out a new array of *n new strings: the
// relative paths, sorted by byte, with a "/" after each directory. A symbolic
// link is listed, but it is never followed. It returns 0. On an error it
// returns -1 and sets errno: ENOENT for a missing root, ENOTDIR for a root
// that is not a directory, or the error of another call.
int list_entries(const char *root, bool recursive, char ***out, size_t *n);

// free_entries frees the array of list_entries and its strings.
void free_entries(char **entries, size_t n);

#endif
test_list_entries.c 131 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

#define _XOPEN_SOURCE 700

#include "list_entries.h"

#include <errno.h>
#include <fcntl.h>
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#define MAX 8

struct test_case {
    const char *name;
    const char *tree[MAX];
    bool recursive;
    const char *want[MAX];
};

static const struct test_case cases[] = {
    {"flat", {"b.txt", "a.txt", "c.txt"}, false, {"a.txt", "b.txt", "c.txt"}},
    {"nested",
     {"docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"},
     true,
     {"docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"}},
    {"nested-shallow",
     {"docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"},
     false,
     {"docs/", "readme.md"}},
    {"empty", {0}, true, {0}},
    {"empty-subdir", {"empty/"}, true, {"empty/"}},
    {"hidden", {".env", ".git/", ".git/config", "main.go"}, true, {".env", ".git/", ".git/config", "main.go"}},
    {"case-order", {"a.txt", "B.txt", "c.txt"}, false, {"B.txt", "a.txt", "c.txt"}},
    {"dot-before-slash", {"a/", "a/x", "a.txt", "a-b"}, true, {"a-b", "a.txt", "a/", "a/x"}},
    {"symlink-to-dir", {"real/", "real/f", "link -> real"}, true, {"link", "real/", "real/f"}},
    {"symlink-to-file", {"f", "g -> f"}, true, {"f", "g"}},
    {"broken-symlink", {"dangling -> nowhere"}, true, {"dangling"}},
    {"symlink-loop", {"d/", "d/up -> .."}, true, {"d/", "d/up"}},
    {"spaces", {"my file.txt", "two  spaces/", "two  spaces/x"}, true, {"my file.txt", "two  spaces/", "two  spaces/x"}},
    {"non-ascii", {"\xc3\xa9t\xc3\xa9.txt", "zebra.txt", "apple.txt"}, false, {"apple.txt", "zebra.txt", "\xc3\xa9t\xc3\xa9.txt"}},
};

static const char *root = "list_entries_tree";

static int remove_one(const char *path, const struct stat *st, int flag, struct FTW *ftw) {
    (void)st;
    (void)flag;
    (void)ftw;
    return remove(path);
}

static void make_tree(const char *const *tree) {
    nftw(root, remove_one, 16, FTW_DEPTH | FTW_PHYS);
    if (mkdir(root, 0755) != 0) {
        perror("mkdir");
        exit(1);
    }
    char path[256];
    for (size_t i = 0; i < MAX && tree[i] != NULL; i++) {
        const char *entry = tree[i];
        const char *arrow = strstr(entry, " -> ");
        int rc;
        if (arrow != NULL) {
            snprintf(path, sizeof path, "%s/%.*s", root, (int)(arrow - entry), entry);
            rc = symlink(arrow + 4, path);
        } else {
            snprintf(path, sizeof path, "%s/%s", root, entry);
            size_t len = strlen(entry);
            if (entry[len - 1] == '/') {
                rc = mkdir(path, 0755);
            } else {
                int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0644);
                rc = fd < 0 ? -1 : close(fd);
            }
        }
        if (rc != 0) {
            perror(path);
            exit(1);
        }
    }
}

int main(void) {
    int failures = 0;
    for (size_t c = 0; c < sizeof cases / sizeof cases[0]; c++) {
        const struct test_case *tc = &cases[c];
        make_tree(tc->tree);
        char **got;
        size_t n;
        if (list_entries(root, tc->recursive, &got, &n) != 0) {
            fprintf(stderr, "case %s: %s\n", tc->name, strerror(errno));
            failures++;
            continue;
        }
        size_t want_n = 0;
        while (want_n < MAX && tc->want[want_n] != NULL) want_n++;
        bool ok = n == want_n;
        for (size_t i = 0; ok && i < n; i++) ok = strcmp(got[i], tc->want[i]) == 0;
        if (!ok) {
            fprintf(stderr, "case %s: got", tc->name);
            for (size_t i = 0; i < n; i++) fprintf(stderr, " [%s]", got[i]);
            fprintf(stderr, "\n");
            failures++;
        }
        free_entries(got, n);
    }

    make_tree((const char *const[]){"notes.txt", NULL});
    char **got;
    size_t n;
    errno = 0;
    if (list_entries("list_entries_tree/missing", true, &got, &n) != -1 || errno != ENOENT) {
        fprintf(stderr, "case missing: no ENOENT\n");
        failures++;
    }
    errno = 0;
    if (list_entries("list_entries_tree/notes.txt", true, &got, &n) != -1 || errno != ENOTDIR) {
        fprintf(stderr, "case not-a-directory: no ENOTDIR\n");
        failures++;
    }
    nftw(root, remove_one, 16, FTW_DEPTH | FTW_PHYS);
    if (failures > 0) return 1;
    puts("ok");
    return 0;
}
ListEntries.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

/// <summary>Lists the entries of a directory, or of a whole tree.</summary>
public static class ListEntries
{
    private static readonly EnumerationOptions Options = new()
    {
        // The default skips Hidden and System. On Unix, a name that starts with "." is Hidden.
        AttributesToSkip = 0,
        // The default ignores the directories that it cannot open.
        IgnoreInaccessible = false,
        // RecurseSubdirectories follows a symbolic link to a directory, so the code recurses itself.
        RecurseSubdirectories = false,
    };

    /// <summary>
    /// Returns the relative paths of the entries under root, sorted by code point. A directory has
    /// a "/" at the end. A symbolic link is listed, but it is never followed.
    /// </summary>
    /// <exception cref="DirectoryNotFoundException">root does not exist.</exception>
    /// <exception cref="IOException">root is a file.</exception>
    public static List<string> List(string root, bool recursive)
    {
        if (File.Exists(root))
        {
            throw new IOException($"{root}: not a directory");
        }
        var output = new List<string>();
        Walk(new DirectoryInfo(root), "", recursive, output);
        // Ordinal order compares UTF-16 code units. That is code point order
        // for names with no characters outside the Basic Multilingual Plane.
        output.Sort(StringComparer.Ordinal);
        return output;
    }

    private static void Walk(DirectoryInfo dir, string prefix, bool recursive, List<string> output)
    {
        foreach (FileSystemInfo info in dir.EnumerateFileSystemInfos("*", Options))
        {
            // LinkTarget is null for an entry that is not a symbolic link.
            if (info is DirectoryInfo sub && info.LinkTarget is null)
            {
                output.Add(prefix + info.Name + "/");
                if (recursive)
                {
                    Walk(sub, prefix + info.Name + "/", recursive, output);
                }
            }
            else
            {
                output.Add(prefix + info.Name);
            }
        }
    }
}
ListEntriesTests.cs 72 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

using Xunit;

public sealed class ListEntriesTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("list-entries-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    private void MakeTree(string[] tree)
    {
        foreach (string entry in tree)
        {
            int arrow = entry.IndexOf(" -> ", StringComparison.Ordinal);
            if (arrow >= 0)
            {
                File.CreateSymbolicLink(Path.Combine(dir, entry[..arrow]), entry[(arrow + 4)..]);
            }
            else if (entry.EndsWith('/'))
            {
                Directory.CreateDirectory(Path.Combine(dir, entry));
            }
            else
            {
                File.WriteAllBytes(Path.Combine(dir, entry), []);
            }
        }
    }

    private static readonly string[] Tree = ["docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"];

    public static TheoryData<string, string[], bool, string[]> Cases => new()
    {
        { "flat", ["b.txt", "a.txt", "c.txt"], false, ["a.txt", "b.txt", "c.txt"] },
        { "nested", Tree, true, Tree },
        { "nested-shallow", Tree, false, ["docs/", "readme.md"] },
        { "empty", [], true, [] },
        { "empty-subdir", ["empty/"], true, ["empty/"] },
        { "hidden", [".env", ".git/", ".git/config", "main.go"], true, [".env", ".git/", ".git/config", "main.go"] },
        { "case-order", ["a.txt", "B.txt", "c.txt"], false, ["B.txt", "a.txt", "c.txt"] },
        { "dot-before-slash", ["a/", "a/x", "a.txt", "a-b"], true, ["a-b", "a.txt", "a/", "a/x"] },
        { "symlink-to-dir", ["real/", "real/f", "link -> real"], true, ["link", "real/", "real/f"] },
        { "symlink-to-file", ["f", "g -> f"], true, ["f", "g"] },
        { "broken-symlink", ["dangling -> nowhere"], true, ["dangling"] },
        { "symlink-loop", ["d/", "d/up -> .."], true, ["d/", "d/up"] },
        { "spaces", ["my file.txt", "two  spaces/", "two  spaces/x"], true, ["my file.txt", "two  spaces/", "two  spaces/x"] },
        { "non-ascii", ["été.txt", "zebra.txt", "apple.txt"], false, ["apple.txt", "zebra.txt", "été.txt"] },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Lists(string name, string[] tree, bool recursive, string[] want)
    {
        Assert.False(string.IsNullOrEmpty(name));
        MakeTree(tree);
        Assert.Equal(want, ListEntries.List(dir, recursive));
    }

    [Fact]
    public void Missing() =>
        Assert.Throws<DirectoryNotFoundException>(() => ListEntries.List(Path.Combine(dir, "missing"), true));

    [Fact]
    public void NotADirectory()
    {
        MakeTree(["notes.txt"]);
        var e = Assert.ThrowsAny<IOException>(() => ListEntries.List(Path.Combine(dir, "notes.txt"), true));
        Assert.IsNotType<DirectoryNotFoundException>(e);
    }
}
listEntries.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

import { readdir } from "node:fs/promises";
import { join } from "node:path";

/**
 * Returns the relative paths of the entries under root. A directory has a "/"
 * at the end. A symbolic link is listed, but it is never followed.
 * @param {string} root
 * @param {boolean} recursive
 * @returns {Promise<string[]>}
 */
export async function listEntries(root, recursive) {
  const out = [];
  async function walk(dir, prefix) {
    for (const entry of await readdir(dir, { withFileTypes: true })) {
      // isDirectory is false for a symbolic link, also for a link to a directory.
      if (entry.isDirectory()) {
        out.push(`${prefix}${entry.name}/`);
        if (recursive) await walk(join(dir, entry.name), `${prefix}${entry.name}/`);
      } else {
        out.push(prefix + entry.name);
      }
    }
  }
  await walk(root, "");
  // The default sort compares UTF-16 code units. That is code point order
  // for names with no characters outside the Basic Multilingual Plane.
  return out.sort();
}
listEntries.test.js 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { listEntries } from "./listEntries.js";

const TREE = ["docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"];

const CASES = {
  flat: [["b.txt", "a.txt", "c.txt"], false, ["a.txt", "b.txt", "c.txt"]],
  nested: [TREE, true, TREE],
  "nested-shallow": [TREE, false, ["docs/", "readme.md"]],
  empty: [[], true, []],
  "empty-subdir": [["empty/"], true, ["empty/"]],
  hidden: [[".env", ".git/", ".git/config", "main.go"], true, [".env", ".git/", ".git/config", "main.go"]],
  "case-order": [["a.txt", "B.txt", "c.txt"], false, ["B.txt", "a.txt", "c.txt"]],
  "dot-before-slash": [["a/", "a/x", "a.txt", "a-b"], true, ["a-b", "a.txt", "a/", "a/x"]],
  "symlink-to-dir": [["real/", "real/f", "link -> real"], true, ["link", "real/", "real/f"]],
  "symlink-to-file": [["f", "g -> f"], true, ["f", "g"]],
  "broken-symlink": [["dangling -> nowhere"], true, ["dangling"]],
  "symlink-loop": [["d/", "d/up -> .."], true, ["d/", "d/up"]],
  spaces: [["my file.txt", "two  spaces/", "two  spaces/x"], true, ["my file.txt", "two  spaces/", "two  spaces/x"]],
  "non-ascii": [["été.txt", "zebra.txt", "apple.txt"], false, ["apple.txt", "zebra.txt", "été.txt"]],
};

const base = mkdtempSync(join(tmpdir(), "list-entries-"));
after(() => rmSync(base, { recursive: true, force: true }));

let count = 0;
function makeTree(tree) {
  const root = join(base, String(count++));
  mkdirSync(root);
  for (const entry of tree) {
    if (entry.includes(" -> ")) {
      const [name, target] = entry.split(" -> ");
      symlinkSync(target, join(root, name));
    } else if (entry.endsWith("/")) {
      mkdirSync(join(root, entry));
    } else {
      writeFileSync(join(root, entry), "");
    }
  }
  return root;
}

for (const [name, [tree, recursive, want]] of Object.entries(CASES)) {
  test(name, async () => {
    assert.deepEqual(await listEntries(makeTree(tree), recursive), want);
  });
}

test("missing", async () => {
  await assert.rejects(listEntries(join(makeTree([]), "missing"), true), { code: "ENOENT" });
});

test("not-a-directory", async () => {
  await assert.rejects(listEntries(join(makeTree(["notes.txt"]), "notes.txt"), true), { code: "ENOTDIR" });
});
listEntries.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

import { readdir } from "node:fs/promises";
import { join } from "node:path";

/**
 * Returns the relative paths of the entries under root. A directory has a "/"
 * at the end. A symbolic link is listed, but it is never followed.
 */
export async function listEntries(root: string, recursive: boolean): Promise<string[]> {
  const out: string[] = [];
  async function walk(dir: string, prefix: string): Promise<void> {
    for (const entry of await readdir(dir, { withFileTypes: true })) {
      // isDirectory is false for a symbolic link, also for a link to a directory.
      if (entry.isDirectory()) {
        out.push(`${prefix}${entry.name}/`);
        if (recursive) await walk(join(dir, entry.name), `${prefix}${entry.name}/`);
      } else {
        out.push(prefix + entry.name);
      }
    }
  }
  await walk(root, "");
  // The default sort compares UTF-16 code units. That is code point order
  // for names with no characters outside the Basic Multilingual Plane.
  return out.sort();
}
listEntries.test.ts 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { listEntries } from "./listEntries.ts";

const TREE = ["docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"];

const CASES: Record<string, [string[], boolean, string[]]> = {
  flat: [["b.txt", "a.txt", "c.txt"], false, ["a.txt", "b.txt", "c.txt"]],
  nested: [TREE, true, TREE],
  "nested-shallow": [TREE, false, ["docs/", "readme.md"]],
  empty: [[], true, []],
  "empty-subdir": [["empty/"], true, ["empty/"]],
  hidden: [[".env", ".git/", ".git/config", "main.go"], true, [".env", ".git/", ".git/config", "main.go"]],
  "case-order": [["a.txt", "B.txt", "c.txt"], false, ["B.txt", "a.txt", "c.txt"]],
  "dot-before-slash": [["a/", "a/x", "a.txt", "a-b"], true, ["a-b", "a.txt", "a/", "a/x"]],
  "symlink-to-dir": [["real/", "real/f", "link -> real"], true, ["link", "real/", "real/f"]],
  "symlink-to-file": [["f", "g -> f"], true, ["f", "g"]],
  "broken-symlink": [["dangling -> nowhere"], true, ["dangling"]],
  "symlink-loop": [["d/", "d/up -> .."], true, ["d/", "d/up"]],
  spaces: [["my file.txt", "two  spaces/", "two  spaces/x"], true, ["my file.txt", "two  spaces/", "two  spaces/x"]],
  "non-ascii": [["été.txt", "zebra.txt", "apple.txt"], false, ["apple.txt", "zebra.txt", "été.txt"]],
};

const base = mkdtempSync(join(tmpdir(), "list-entries-"));
after(() => rmSync(base, { recursive: true, force: true }));

let count = 0;
function makeTree(tree: string[]): string {
  const root = join(base, String(count++));
  mkdirSync(root);
  for (const entry of tree) {
    if (entry.includes(" -> ")) {
      const [name, target] = entry.split(" -> ") as [string, string];
      symlinkSync(target, join(root, name));
    } else if (entry.endsWith("/")) {
      mkdirSync(join(root, entry));
    } else {
      writeFileSync(join(root, entry), "");
    }
  }
  return root;
}

for (const [name, [tree, recursive, want]] of Object.entries(CASES)) {
  test(name, async () => {
    assert.deepEqual(await listEntries(makeTree(tree), recursive), want);
  });
}

test("missing", async () => {
  await assert.rejects(listEntries(join(makeTree([]), "missing"), true), { code: "ENOENT" });
});

test("not-a-directory", async () => {
  await assert.rejects(listEntries(join(makeTree(["notes.txt"]), "notes.txt"), true), { code: "ENOTDIR" });
});
list_entries.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

// Package listentries lists the entries of a directory, or of a whole tree.
package listentries

import (
	"os"
	"path/filepath"
	"slices"
)

// ListEntries returns the relative paths of the entries under root, sorted by
// code point. A directory has a "/" at the end. A symbolic link is listed, but
// it is never followed. The error wraps fs.ErrNotExist for a missing root and
// syscall.ENOTDIR for a root that is not a directory.
func ListEntries(root string, recursive bool) ([]string, error) {
	var out []string
	var walk func(dir, prefix string) error
	walk = func(dir, prefix string) error {
		// os.ReadDir sorts the entries by name. The type of an entry comes
		// from the directory itself, so a symbolic link is not a directory.
		entries, err := os.ReadDir(dir)
		if err != nil {
			return err
		}
		for _, e := range entries {
			if !e.IsDir() {
				out = append(out, prefix+e.Name())
				continue
			}
			out = append(out, prefix+e.Name()+"/")
			if recursive {
				if err := walk(filepath.Join(dir, e.Name()), prefix+e.Name()+"/"); err != nil {
					return err
				}
			}
		}
		return nil
	}
	if err := walk(root, ""); err != nil {
		return nil, err
	}
	// Each directory is in order, but "a.txt" must come before "a/x".
	slices.Sort(out)
	return out, nil
}
list_entries_test.go 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

package listentries

import (
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"syscall"
	"testing"
)

// makeTree makes each entry of the tree in a new directory and returns its path.
func makeTree(t *testing.T, tree []string) string {
	t.Helper()
	root := t.TempDir()
	for _, entry := range tree {
		var err error
		if name, target, ok := strings.Cut(entry, " -> "); ok {
			err = os.Symlink(target, filepath.Join(root, name))
		} else if strings.HasSuffix(entry, "/") {
			err = os.Mkdir(filepath.Join(root, entry), 0o755)
		} else {
			err = os.WriteFile(filepath.Join(root, entry), nil, 0o644)
		}
		if err != nil {
			t.Fatal(err)
		}
	}
	return root
}

func TestCases(t *testing.T) {
	tree := []string{"docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"}
	cases := []struct {
		name      string
		tree      []string
		recursive bool
		want      []string
	}{
		{"flat", []string{"b.txt", "a.txt", "c.txt"}, false, []string{"a.txt", "b.txt", "c.txt"}},
		{"nested", tree, true, tree},
		{"nested-shallow", tree, false, []string{"docs/", "readme.md"}},
		{"empty", nil, true, nil},
		{"empty-subdir", []string{"empty/"}, true, []string{"empty/"}},
		{"hidden", []string{".env", ".git/", ".git/config", "main.go"}, true, []string{".env", ".git/", ".git/config", "main.go"}},
		{"case-order", []string{"a.txt", "B.txt", "c.txt"}, false, []string{"B.txt", "a.txt", "c.txt"}},
		{"dot-before-slash", []string{"a/", "a/x", "a.txt", "a-b"}, true, []string{"a-b", "a.txt", "a/", "a/x"}},
		{"symlink-to-dir", []string{"real/", "real/f", "link -> real"}, true, []string{"link", "real/", "real/f"}},
		{"symlink-to-file", []string{"f", "g -> f"}, true, []string{"f", "g"}},
		{"broken-symlink", []string{"dangling -> nowhere"}, true, []string{"dangling"}},
		{"symlink-loop", []string{"d/", "d/up -> .."}, true, []string{"d/", "d/up"}},
		{"spaces", []string{"my file.txt", "two  spaces/", "two  spaces/x"}, true, []string{"my file.txt", "two  spaces/", "two  spaces/x"}},
		{"non-ascii", []string{"été.txt", "zebra.txt", "apple.txt"}, false, []string{"apple.txt", "zebra.txt", "été.txt"}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := ListEntries(makeTree(t, c.tree), c.recursive)
			if err != nil || !slices.Equal(got, c.want) {
				t.Errorf("ListEntries = %q, %v; want %q, nil", got, err, c.want)
			}
		})
	}
}

func TestMissing(t *testing.T) {
	_, err := ListEntries(filepath.Join(t.TempDir(), "missing"), true)
	if !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("err = %v, want fs.ErrNotExist", err)
	}
}

func TestNotADirectory(t *testing.T) {
	root := makeTree(t, []string{"notes.txt"})
	_, err := ListEntries(filepath.Join(root, "notes.txt"), true)
	if !errors.Is(err, syscall.ENOTDIR) {
		t.Errorf("err = %v, want syscall.ENOTDIR", err)
	}
}
list_entries.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

use std::fs;
use std::io;
use std::path::Path;

/// Returns the relative paths of the entries under `root`, sorted by code
/// point. A directory has a `/` at the end. A symbolic link is listed, but it
/// is never followed.
///
/// # Errors
///
/// An error of kind `NotFound` if `root` does not exist, `NotADirectory` if it
/// is not a directory, and `InvalidData` for a name that is not UTF-8.
pub fn list_entries(root: &Path, recursive: bool) -> io::Result<Vec<String>> {
    let mut out = Vec::new();
    walk(root, "", recursive, &mut out)?;
    // read_dir gives the entries in an order that depends on the platform.
    out.sort();
    Ok(out)
}

fn walk(dir: &Path, prefix: &str, recursive: bool, out: &mut Vec<String>) -> io::Result<()> {
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let name = entry
            .file_name()
            .into_string()
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "a name is not UTF-8"))?;
        // DirEntry::file_type does not follow a symbolic link.
        if entry.file_type()?.is_dir() {
            let path = format!("{prefix}{name}/");
            out.push(path.clone());
            if recursive {
                walk(&entry.path(), &path, recursive, out)?;
            }
        } else {
            out.push(format!("{prefix}{name}"));
        }
    }
    Ok(())
}
tests/list_entries_test.rs 99 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/list-files-in-a-directory/.

use std::fs;
use std::io::ErrorKind;
use std::os::unix::fs::symlink;
use std::path::PathBuf;

use algo_list_files_in_a_directory::list_entries;

/// A new directory that is removed when the value is dropped.
struct Tree(PathBuf);

impl Drop for Tree {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

/// Makes each entry of the tree in a new directory.
fn make_tree(name: &str, tree: &[&str]) -> Tree {
    let root = std::env::temp_dir().join(format!("list-entries-{}-{name}", std::process::id()));
    let _ = fs::remove_dir_all(&root);
    fs::create_dir(&root).unwrap();
    for entry in tree {
        if let Some((link, target)) = entry.split_once(" -> ") {
            symlink(target, root.join(link)).unwrap();
        } else if entry.ends_with('/') {
            fs::create_dir(root.join(entry)).unwrap();
        } else {
            fs::write(root.join(entry), b"").unwrap();
        }
    }
    Tree(root)
}

#[test]
fn cases() {
    let tree = ["docs/", "docs/guide.md", "docs/img/", "docs/img/logo.png", "readme.md"];
    let cases: [(&str, &[&str], bool, &[&str]); 14] = [
        ("flat", &["b.txt", "a.txt", "c.txt"], false, &["a.txt", "b.txt", "c.txt"]),
        ("nested", &tree, true, &tree),
        ("nested-shallow", &tree, false, &["docs/", "readme.md"]),
        ("empty", &[], true, &[]),
        ("empty-subdir", &["empty/"], true, &["empty/"]),
        (
            "hidden",
            &[".env", ".git/", ".git/config", "main.go"],
            true,
            &[".env", ".git/", ".git/config", "main.go"],
        ),
        ("case-order", &["a.txt", "B.txt", "c.txt"], false, &["B.txt", "a.txt", "c.txt"]),
        (
            "dot-before-slash",
            &["a/", "a/x", "a.txt", "a-b"],
            true,
            &["a-b", "a.txt", "a/", "a/x"],
        ),
        (
            "symlink-to-dir",
            &["real/", "real/f", "link -> real"],
            true,
            &["link", "real/", "real/f"],
        ),
        ("symlink-to-file", &["f", "g -> f"], true, &["f", "g"]),
        ("broken-symlink", &["dangling -> nowhere"], true, &["dangling"]),
        ("symlink-loop", &["d/", "d/up -> .."], true, &["d/", "d/up"]),
        (
            "spaces",
            &["my file.txt", "two  spaces/", "two  spaces/x"],
            true,
            &["my file.txt", "two  spaces/", "two  spaces/x"],
        ),
        (
            "non-ascii",
            &["été.txt", "zebra.txt", "apple.txt"],
            false,
            &["apple.txt", "zebra.txt", "été.txt"],
        ),
    ];
    for (name, tree, recursive, want) in cases {
        let got = list_entries(&make_tree(name, tree).0, recursive).unwrap();
        assert_eq!(got, want, "case {name}");
    }
}

#[test]
fn missing() {
    let root = make_tree("missing", &[]);
    let err = list_entries(&root.0.join("missing"), true).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}

#[test]
fn not_a_directory() {
    let root = make_tree("not-a-directory", &["notes.txt"]);
    let err = list_entries(&root.0.join("notes.txt"), true).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotADirectory);
}
list_entries.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/list-files-in-a-directory/.

# list_entries [-r] DIR prints the relative path of each entry under DIR, one
# per line, sorted by byte. With -r it lists the whole tree. A directory has a
# "/" at the end. A symbolic link is listed, but it is never followed. It
# returns 1 with a message on stderr if DIR is missing or is not a directory.
list_entries() {
  local recursive=0
  if [[ $1 == -r ]]; then
    recursive=1
    shift
  fi
  if [[ ! -e $1 && ! -L $1 ]]; then
    printf 'list_entries: %s: No such file or directory\n' "$1" >&2
    return 1
  fi
  if [[ ! -d $1 ]]; then
    printf 'list_entries: %s: Not a directory\n' "$1" >&2
    return 1
  fi
  _list_entries_walk "$1" "" "$recursive" | LC_ALL=C sort
}

# _list_entries_walk DIR PREFIX RECURSIVE runs in a subshell, so the shopt
# settings do not leak into the caller.
_list_entries_walk() (
  # dotglob matches names that start with ".", but never "." and "..".
  # nullglob makes "*" expand to nothing in an empty directory.
  shopt -s dotglob nullglob
  local path rel
  for path in "$1"/*; do
    rel=$2${path##*/}
    # -d follows a symbolic link, so test -L too.
    if [[ -d $path && ! -L $path ]]; then
      printf '%s/\n' "$rel"
      if (($3)); then
        _list_entries_walk "$path" "$rel/" 1
      fi
    else
      printf '%s\n' "$rel"
    fi
  done
)
test_list_entries.bats 68 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/list-files-in-a-directory/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/list_entries.sh"
  root="$BATS_TEST_TMPDIR/tree"
  mkdir "$root"
}

make_tree() { # make_tree ENTRY...
  local entry
  for entry in "$@"; do
    if [[ $entry == *" -> "* ]]; then
      ln -s "${entry#* -> }" "$root/${entry%% -> *}"
    elif [[ $entry == */ ]]; then
      mkdir "$root/$entry"
    else
      : >"$root/$entry"
    fi
  done
}

check() { # check FLAGS WANT, after make_tree
  run list_entries $1 "$root"
  [ "$status" -eq 0 ]
  [ "$output" = "$2" ]
}

nl=$'\n'
tree=(docs/ docs/guide.md docs/img/ docs/img/logo.png readme.md)

@test "flat" { make_tree b.txt a.txt c.txt; check "" "a.txt${nl}b.txt${nl}c.txt"; }
@test "nested" { make_tree "${tree[@]}"; check -r "docs/${nl}docs/guide.md${nl}docs/img/${nl}docs/img/logo.png${nl}readme.md"; }
@test "nested-shallow" { make_tree "${tree[@]}"; check "" "docs/${nl}readme.md"; }
@test "empty" { check -r ""; }
@test "empty-subdir" { make_tree empty/; check -r "empty/"; }
@test "hidden" { make_tree .env .git/ .git/config main.go; check -r ".env${nl}.git/${nl}.git/config${nl}main.go"; }
@test "case-order" { make_tree a.txt B.txt c.txt; check "" "B.txt${nl}a.txt${nl}c.txt"; }
@test "dot-before-slash" { make_tree a/ a/x a.txt a-b; check -r "a-b${nl}a.txt${nl}a/${nl}a/x"; }
@test "symlink-to-dir" { make_tree real/ real/f "link -> real"; check -r "link${nl}real/${nl}real/f"; }
@test "symlink-to-file" { make_tree f "g -> f"; check -r "f${nl}g"; }
@test "broken-symlink" { make_tree "dangling -> nowhere"; check -r "dangling"; }
@test "symlink-loop" { make_tree d/ "d/up -> .."; check -r "d/${nl}d/up"; }
@test "spaces" { make_tree "my file.txt" "two  spaces/" "two  spaces/x"; check -r "my file.txt${nl}two  spaces/${nl}two  spaces/x"; }
@test "non-ascii" { make_tree été.txt zebra.txt apple.txt; check "" "apple.txt${nl}zebra.txt${nl}été.txt"; }

@test "missing" {
  run --separate-stderr list_entries -r "$root/missing"
  [ "$status" -eq 1 ]
  [ -z "$output" ]
}

@test "not-a-directory" {
  make_tree notes.txt
  run --separate-stderr list_entries -r "$root/notes.txt"
  [ "$status" -eq 1 ]
  [ -z "$output" ]
}

@test "shell options unchanged" {
  shopt -u dotglob nullglob
  list_entries "$root" >/dev/null
  ! shopt -q dotglob
  ! shopt -q nullglob
}

References

  1. The Open Group, POSIX.1-2024, readdir, Description, the entries for dot and dot-dot
  2. The Open Group, POSIX.1-2024, fstat, fstatat, lstat and stat, Description, AT_SYMLINK_NOFOLLOW
  3. The Python Standard Library, os, scandir, os.scandir, os.DirEntry.is_dir, os.walk
  4. Node.js documentation, File system, fsPromises.readdir, the withFileTypes option; Class fs.Dirent, dirent.isDirectory and dirent.isSymbolicLink
  5. Java SE 25 API, java.nio.file.Files, walk(Path, int, FileVisitOption...), walkFileTree (FileSystemLoopException)
  6. .NET API reference, EnumerationOptions.AttributesToSkip, Property Value
  7. .NET API reference, EnumerationOptions.IgnoreInaccessible, Property Value
  8. .NET API reference, FileAttributes, Remarks, the Hidden attribute on Unix
  9. .NET API reference, FileSystemInfo.LinkTarget, Property Value
  10. Go standard library, package os, ReadDir, File.ReadDir
  11. The Rust Standard Library, std::fs::read_dir, Platform-specific behavior
  12. The Rust Standard Library, std::fs::DirEntry, file_type
  13. cppreference.com, std::filesystem::recursive_directory_iterator
  14. cppreference.com, std::filesystem::directory_iterator
  15. cppreference.com, std::filesystem::directory_entry::is_directory
  16. GNU Bash Reference Manual, Filename Expansion, Filename Expansion; The Shopt Builtin, dotglob, globskipdots and nullglob

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 9 of 10 languages in this build.