readdir

readdir(?resource $dir_handle = null): string|false

Reads one entry at a time from a directory handle (streaming, memory-friendly for huge directories); omitting the handle argument is deprecated since PHP 8.5.

C C23

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

static int cmp(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

int main(void) {
    /* fixed fixture dir (POSIX mkdir needs sys/stat.h explicitly) */
    const char *dirpath = "readdir_demo_c_a20";
    mkdir(dirpath, 0755);
    const char *files[] = {"zeta.txt", "alpha.txt", "mid.txt"};
    char path[256];
    for (int i = 0; i < 3; i++) {
        snprintf(path, sizeof(path), "%s/%s", dirpath, files[i]);
        FILE *f = fopen(path, "w");
        fputs("x", f);
        fclose(f);
    }
    /* streaming: readdir returns one entry per call, order unspecified */
    DIR *dir = opendir(dirpath);
    const char *names[64];
    size_t n = 0;
    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        names[n++] = strdup(entry->d_name); /* d_name points to reused storage */
    }
    closedir(dir);
    /* deterministic output: collect, sort, then print */
    qsort(names, n, sizeof(names[0]), cmp);
    for (size_t i = 0; i < n; i++) {
        printf("%s%s", names[i], i + 1 < n ? "," : "\n");
    }
    return 0;
}
Output
.,..,alpha.txt,mid.txt,zeta.txt

C++ C++26

C++26
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

namespace fs = std::filesystem;

int main() {
    fs::path dir = fs::temp_directory_path() / "readdir_demo_cpp_a20";
    fs::remove_all(dir);
    fs::create_directory(dir);
    for (const char* name : {"zeta.txt", "alpha.txt", "mid.txt"}) {
        std::ofstream(dir / name) << "x";
    }
    // directory_iterator is naturally streaming (one entry per increment)
    std::vector<std::string> names;
    for (const auto& e : fs::directory_iterator(dir)) {
        names.push_back(e.path().filename().string());
    }
    std::sort(names.begin(), names.end());
    for (size_t i = 0; i < names.size(); ++i) {
        std::cout << names[i] << (i + 1 < names.size() ? "," : "\n");
    }
    std::cout << "count ok: " << (names.size() == 3 ? "yes" : "no");
    return 0;
}
Output
alpha.txt,mid.txt,zeta.txt
count ok: yes

C# v11.0.100

v11.0.100
// Directory.EnumerateFileSystemEntries is lazy (streaming);
// GetFileSystemEntries materializes - the .NET naming pair maps exactly
// onto this entry's streaming-vs-materialized theme
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

var dir = Path.Combine(Path.GetTempPath(), "readdir_demo_cs_a20");
if (Directory.Exists(dir)) Directory.Delete(dir, true);
Directory.CreateDirectory(dir);
foreach (var name in new[] { "zeta.txt", "alpha.txt", "mid.txt" }) {
    File.WriteAllText(Path.Combine(dir, name), "x");
}
var names = Directory.EnumerateFileSystemEntries(dir)
    .Select(p => Path.GetFileName(p))
    .ToList();
names.Sort();
Console.WriteLine(string.Join(",", names));
Console.WriteLine(Directory.GetFileSystemEntries(dir).Length == 3);
Output
alpha.txt,mid.txt,zeta.txt
True

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os"
	"sort"
)

func main() {
	dir, _ := os.MkdirTemp("", "readdir_a20_go")
	defer os.RemoveAll(dir)
	for _, name := range []string{"zeta.txt", "alpha.txt", "mid.txt"} {
		_ = os.WriteFile(dir+string(os.PathSeparator)+name, []byte("x"), 0o644)
	}
	// os.ReadDir materializes the whole listing (already sorted)
	entries, _ := os.ReadDir(dir)
	names := make([]string, 0, len(entries))
	for _, e := range entries {
		names = append(names, e.Name())
	}
	sort.Strings(names)
	fmt.Println(len(entries) == 3 && names[0] == "alpha.txt")
	// f.ReadDir(n) streams: at most n entries per call, io.EOF ends the stream
	f, _ := os.Open(dir)
	defer f.Close()
	count := 0
	for {
		batch, err := f.ReadDir(2)
		count += len(batch)
		if err != nil {
			break
		}
	}
	fmt.Println(count == 3)
}
Output
true
true

Java v27.0.1

v27.0.1
// Files.list returns a lazy Stream (streaming); collecting it
// materializes. try-with-resources closes the directory stream.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Main {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("readdir_a20_java");
        for (String name : List.of("zeta.txt", "alpha.txt", "mid.txt")) {
            Files.writeString(dir.resolve(name), "x");
        }
        List<String> names;
        try (Stream<Path> stream = Files.list(dir)) { // streaming
            names = stream.map(p -> p.getFileName().toString()).collect(Collectors.toList());
        }
        Collections.sort(names);
        System.out.println(String.join(",", names));
        try (Stream<Path> stream = Files.list(dir)) {
            System.out.println(stream.count() == 3);
        }
    }
}
Output
alpha.txt,mid.txt,zeta.txt
true

JavaScript v26.13.1

v26.13.1
// fs.opendirSync gives a streaming handle; fs.readdirSync materializes
// the whole listing - the same streaming-vs-materialized pair as PHP
// readdir vs scandir
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");

const dir = fs.mkdtempSync(path.join(os.tmpdir(), "readdir_a20_js"));
for (const name of ["zeta.txt", "alpha.txt", "mid.txt"]) {
    fs.writeFileSync(path.join(dir, name), "x");
}
const handle = fs.opendirSync(dir);
const names = [];
for (;;) {
    const entry = handle.readSync(); // one entry at a time (streaming)
    if (entry === null) break;
    names.push(entry.name);
}
handle.closeSync();
names.sort();
console.log(names.join(","));
console.log(fs.readdirSync(dir).length === 3);
Output
alpha.txt,mid.txt,zeta.txt
true

PHP v8.6.0

v8.6.0
// readdir: streaming - one entry at a time (memory-friendly for huge
// dirs); scandir: materialized - the whole listing at once.
// Deprecation since 8.5: omitting the handle argument - always pass it
$dirPath = sys_get_temp_dir() . "/readdir_demo_php_a20";
if (!is_dir($dirPath)) mkdir($dirPath);
foreach (["zeta.txt", "alpha.txt", "mid.txt"] as $f) {
    file_put_contents("$dirPath/$f", "x");
}
$h = opendir($dirPath);
$names = [];
while (($entry = readdir($h)) !== false) { // strict !== (false vs "0")
    $names[] = $entry;
}
closedir($h);
sort($names); // readdir order is unspecified - sort for determinism
// readdir returns . and .. too (like the C counterpart)
echo implode(",", $names), "\n";
echo count(scandir($dirPath)) === 5 ? "same set" : "different";
Output
.,..,alpha.txt,mid.txt,zeta.txt
same set

Python v3.15.2

v3.15.2
import os
import tempfile

d = tempfile.mkdtemp(prefix="readdir_a20_py")
for name in ["zeta.txt", "alpha.txt", "mid.txt"]:
    with open(os.path.join(d, name), "w") as fh:
        fh.write("x")

# os.scandir returns an iterator (streaming); os.listdir materializes a list
names = sorted(entry.name for entry in os.scandir(d))
print(",".join(names))
# listdir counterpart: the whole listing in one call; neither includes ./..
print(len(os.listdir(d)) == 3)
Output
alpha.txt,mid.txt,zeta.txt
True

Rust v1.99.1

v1.99.1
// fs::read_dir returns an iterator (naturally streaming); collecting
// into a Vec is the materialization step
use std::fs;

fn main() {
    let dir = std::env::temp_dir().join("readdir_demo_rust_a20");
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    for name in ["zeta.txt", "alpha.txt", "mid.txt"] {
        fs::write(dir.join(name), "x").unwrap();
    }
    let mut names: Vec<String> = fs::read_dir(&dir) // streaming iterator
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect(); // materialize
    names.sort();
    println!("{}", names.join(","));
    println!("{}", fs::read_dir(&dir).unwrap().count() == 3);
    fs::remove_dir_all(&dir).unwrap();
}
Output
alpha.txt,mid.txt,zeta.txt
true

TypeScript v26.13.1

v26.13.1
// Same streaming handle vs materialized list, with types on the entries
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";

const dir = fs.mkdtempSync(path.join(os.tmpdir(), "readdir_a20_ts"));
for (const name of ["zeta.txt", "alpha.txt", "mid.txt"]) {
    fs.writeFileSync(path.join(dir, name), "x");
}
const names: string[] = [];
const handle = fs.opendirSync(dir);
for (let entry = handle.readSync(); entry !== null; entry = handle.readSync()) {
    names.push(entry.name);
}
handle.closeSync();
names.sort();
console.log(names.join(","));
console.log(fs.readdirSync(dir).length === 3);
Output
alpha.txt,mid.txt,zeta.txt
true

Language differences

C: the POSIX opendir/readdir loop — the origin of streaming reads; classic dirty detail: termination can only rely on a NULL return (distinguishing "error" requires clearing errno first); d_name points to internal storage that gets reused, so keeping values across rounds needs strdup; . and .. are included.

C++: C++17 directory_iterator is naturally streaming (one entry per increment), and begin/end make it range-for friendly; no ./..; throws filesystem_error on failure.

C#: the .NET naming maps exactly onto this entry's theme — Directory.EnumerateFileSystemEntries (lazy streaming) vs GetFileSystemEntries (one-shot materialization); order is unspecified, sort it yourself.

Go: since 1.16 os.ReadDir is already materialized (and sorted by filename); streaming requires os.Open plus f.ReadDir(n) batches (example), closed out by io.EOF.

Java: Files.list returns a lazy Stream (streaming); .toList() is the materialization; must be closed explicitly via try-with-resources (the directory stream holds a handle); order is unspecified.

JavaScript: the isomorphic pair — fs.opendirSync streaming handle (readSync() one at a time, null ends it) vs fs.readdirSync materialized listing; no ./..; callback-style fs.readdir and promise-style fs.promises.readdir both materialize.

PHP: the contrast with scandir is the core — readdir streams entry by entry (constant memory for million-file dirs), scandir materializes the whole array at once (echoing iterator_to_array); readdir order is unspecified (filesystem decides), so collect then sort for deterministic output; it returns . and .. (so does scandir; most other languages do not); termination returns false, so the loop condition must be !== false (the "0" filename trap); deprecated since 8.5: calling without the handle (relying on the implicit "last opened directory" state) — teaching point: always pass $h explicitly; hidden global state is an anti-pattern.

Python: os.scandir is an iterator (streaming, with stat caching), os.listdir a materialized list; neither includes ./..; order is filesystem-decided, sort it yourself.

Rust: fs::read_dir returns a ReadDir iterator (naturally streaming), collect() materializes; no ./..; entries are Result<DirEntry> so errors are handled per item.

TypeScript: same as JavaScript (opendirSync streaming / readdirSync materialized, example); the Dirent type makes entry shapes explicit.