RecursiveIteratorIterator
RecursiveIteratorIterator implements OuterIterator
The outer wrapper that flattens a RecursiveIterator (directory tree, nested arrays) into one linear stream: LEAVES_ONLY by default, getDepth() reports level - recursive traversal is a scenario, not a function.
C C23
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
/* C in reverse: nftw(3) is the tree walker - one callback per entry,
FTW_DEPTH gives post-order (used here to delete bottom-up) */
static char found[16][64];
static int found_n = 0;
static const char *root_path = NULL;
static int collect_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
(void)sb;
(void)ftwbuf;
if (typeflag == FTW_F) {
snprintf(found[found_n], sizeof found[0], "%s", fpath + strlen(root_path) + 1);
found_n++;
}
return 0;
}
static int remove_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
(void)sb;
(void)ftwbuf;
return typeflag == FTW_DP ? rmdir(fpath) : unlink(fpath);
}
int main(void) {
char tmpl[] = "/tmp/c_rii_a44_XXXXXX";
char *root = mkdtemp(tmpl);
if (!root) return 1;
root_path = root;
char path[128];
snprintf(path, sizeof path, "%s/a", root);
mkdir(path, 0755);
snprintf(path, sizeof path, "%s/a/sub", root);
mkdir(path, 0755);
snprintf(path, sizeof path, "%s/a/file1.txt", root);
FILE *f = fopen(path, "w");
if (f) { fputs("1", f); fclose(f); }
snprintf(path, sizeof path, "%s/a/sub/file2.txt", root);
f = fopen(path, "w");
if (f) { fputs("2", f); fclose(f); }
snprintf(path, sizeof path, "%s/top.txt", root);
f = fopen(path, "w");
if (f) { fputs("3", f); fclose(f); }
nftw(root, collect_cb, 16, FTW_PHYS);
/* sort the collected relative paths for deterministic output */
for (int i = 1; i < found_n; i++) {
char key[64] = {0};
memcpy(key, found[i], sizeof found[0]);
int j = i - 1;
while (j >= 0 && strcmp(found[j], key) > 0) {
memcpy(found[j + 1], found[j], sizeof found[0]);
j--;
}
memcpy(found[j + 1], key, sizeof found[0]);
}
for (int i = 0; i < found_n; i++) {
printf("%s\n", found[i]);
}
nftw(root, remove_cb, 16, FTW_PHYS | FTW_DEPTH);
return 0;
}
a/file1.txt a/sub/file2.txt top.txt
C++ C++26
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <system_error>
#include <vector>
namespace fs = std::filesystem;
int main() {
// C++ in reverse: recursive_directory_iterator flattens the tree in one
// loop; relativize and sort for a deterministic print order
fs::path root = fs::temp_directory_path() / "cpp_rii_a44";
std::error_code ec;
fs::remove_all(root, ec);
fs::create_directories(root / "a" / "sub");
std::ofstream(root / "a" / "file1.txt") << "1";
std::ofstream(root / "a" / "sub" / "file2.txt") << "2";
std::ofstream(root / "top.txt") << "3";
std::vector<std::string> found;
for (const auto &entry : fs::recursive_directory_iterator(root)) {
if (entry.is_regular_file()) {
found.push_back(fs::relative(entry.path(), root).generic_string());
}
}
std::sort(found.begin(), found.end());
for (const auto &rel : found) {
std::cout << rel << "\n";
}
fs::remove_all(root, ec);
return 0;
}
a/file1.txt a/sub/file2.txt top.txt
C# v11.0.100
using System.Collections.Generic;
using System.IO;
using System.Linq;
// C# in reverse: Directory.EnumerateFiles with AllDirectories is the
// built-in tree walk - lazy, one line, filtering stays in the pipeline
var root = Path.Combine(Path.GetTempPath(), "cs_rii_a44_" + Path.GetRandomFileName());
Directory.CreateDirectory(Path.Combine(root, "a", "sub"));
File.WriteAllText(Path.Combine(root, "a", "file1.txt"), "1");
File.WriteAllText(Path.Combine(root, "a", "sub", "file2.txt"), "2");
File.WriteAllText(Path.Combine(root, "top.txt"), "3");
var found = Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)
.Select(p => Path.GetRelativePath(root, p).Replace('\\', '/'))
.OrderBy(p => p, System.StringComparer.Ordinal)
.ToList();
found.ForEach(Console.WriteLine);
Directory.Delete(root, true);
a/file1.txt a/sub/file2.txt top.txt
Go v1.27.4
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
)
// Go in reverse: filepath.WalkDir is the tree walker - one callback receives
// every entry in lexical order; skip dirs to see files only
func main() {
root, err := os.MkdirTemp("", "go_rii_a44_")
if err != nil {
panic(err)
}
defer os.RemoveAll(root)
if err := os.MkdirAll(filepath.Join(root, "a", "sub"), 0o755); err != nil {
panic(err)
}
os.WriteFile(filepath.Join(root, "a", "file1.txt"), []byte("1"), 0o644)
os.WriteFile(filepath.Join(root, "a", "sub", "file2.txt"), []byte("2"), 0o644)
os.WriteFile(filepath.Join(root, "top.txt"), []byte("3"), 0o644)
found := []string{}
err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
rel, relErr := filepath.Rel(root, p)
if relErr != nil {
return relErr
}
found = append(found, rel)
}
return nil
})
if err != nil {
panic(err)
}
sort.Strings(found)
fmt.Println(strings.Join(found, "\n"))
}
a/file1.txt a/sub/file2.txt top.txt
Java v27.0.1
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
// Java in reverse: Files.walk streams the whole tree lazily;
// filter to regular files and relativize for display
Path root = Files.createTempDirectory("java_rii_a44_");
Files.createDirectories(root.resolve("a/sub"));
Files.write(root.resolve("a/file1.txt"), new byte[] {49});
Files.write(root.resolve("a/sub/file2.txt"), new byte[] {50});
Files.write(root.resolve("top.txt"), new byte[] {51});
List<String> found = new ArrayList<>();
try (var stream = Files.walk(root)) {
stream.filter(Files::isRegularFile)
.map(p -> root.relativize(p).toString().replace('\\', '/'))
.sorted()
.forEach(found::add);
}
System.out.println(String.join("\n", found));
// cleanup: delete children before directories
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path p, BasicFileAttributes a) throws IOException {
Files.delete(p);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path p, IOException e) throws IOException {
Files.delete(p);
return FileVisitResult.CONTINUE;
}
});
}
}
a/file1.txt a/sub/file2.txt top.txt
JavaScript v26.13.1
// JS in reverse: Node ships no tree walker - recurse readdir by hand,
// sorting names so the visit order is deterministic
const fs = require("fs");
const os = require("os");
const path = require("path");
const root = fs.mkdtempSync(path.join(os.tmpdir(), "js_rii_a44_"));
fs.mkdirSync(path.join(root, "a", "sub"), { recursive: true });
fs.writeFileSync(path.join(root, "a", "file1.txt"), "1");
fs.writeFileSync(path.join(root, "a", "sub", "file2.txt"), "2");
fs.writeFileSync(path.join(root, "top.txt"), "3");
function walk(dir, acc) {
for (const name of fs.readdirSync(dir).sort()) {
const p = path.join(dir, name);
if (fs.statSync(p).isDirectory()) walk(p, acc);
else acc.push(path.relative(root, p));
}
return acc;
}
console.log(walk(root, []).join("\n"));
fs.rmSync(root, { recursive: true });
a/file1.txt a/sub/file2.txt top.txt
PHP v8.6.0
// RecursiveIteratorIterator flattens a tree-shaped RecursiveIterator (here a
// directory tree) into one linear stream; LEAVES_ONLY (default) yields files only
$root = sys_get_temp_dir() . "/php_rii_a44_" . uniqid();
mkdir("$root/a/sub", 0777, true);
file_put_contents("$root/a/file1.txt", "1");
file_put_contents("$root/a/sub/file2.txt", "2");
file_put_contents("$root/top.txt", "3");
// getDepth() reports the current nesting level while iterating (top level = 0)
$rii = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)
);
$rows = [];
foreach ($rii as $file) {
$rel = substr($file->getPathname(), strlen($root) + 1);
$rows[] = "$rel depth=" . $rii->getDepth();
}
sort($rows);
echo implode("\n", $rows), "\n";
// Cleanup (best effort): files first, then directories bottom-up
unlink("$root/a/file1.txt");
unlink("$root/a/sub/file2.txt");
unlink("$root/top.txt");
rmdir("$root/a/sub");
rmdir("$root/a");
rmdir($root);
a/file1.txt depth=1 a/sub/file2.txt depth=2 top.txt depth=0
Python v3.15.2
# Python in reverse: os.walk IS the directory-tree iterator - yields
# (dirpath, dirs, files) per level, no wrapper needed
import os
import shutil
import tempfile
root = tempfile.mkdtemp(prefix="py_rii_a44_")
os.makedirs(os.path.join(root, "a", "sub"))
open(os.path.join(root, "a", "file1.txt"), "w").close()
open(os.path.join(root, "a", "sub", "file2.txt"), "w").close()
open(os.path.join(root, "top.txt"), "w").close()
found = []
for dirpath, dirs, files in os.walk(root):
for f in files:
rel = os.path.relpath(os.path.join(dirpath, f), root)
found.append(rel.replace(os.sep, "/"))
found.sort()
print("\n".join(found))
shutil.rmtree(root)
a/file1.txt a/sub/file2.txt top.txt
Rust v1.99.1
// Rust in reverse: std has no tree walker - recurse over read_dir by hand
// and sort names so the order is deterministic (the ecosystem answer is
// the walkdir crate; std keeps this explicit)
use std::fs;
use std::path::{Path, PathBuf};
fn walk(dir: &Path, root: &Path, found: &mut Vec<String>) {
let mut entries: Vec<PathBuf> = fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().path())
.collect();
entries.sort();
for p in entries {
if p.is_dir() {
walk(&p, root, found);
} else {
let rel = p.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
found.push(rel);
}
}
}
fn main() {
let root = std::env::temp_dir().join("rust_rii_a44");
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(root.join("a").join("sub")).unwrap();
fs::write(root.join("a").join("file1.txt"), "1").unwrap();
fs::write(root.join("a").join("sub").join("file2.txt"), "2").unwrap();
fs::write(root.join("top.txt"), "3").unwrap();
let mut found = vec![];
walk(&root, &root, &mut found);
found.sort();
for f in &found {
println!("{}", f);
}
fs::remove_dir_all(&root).unwrap();
}
a/file1.txt a/sub/file2.txt top.txt
TypeScript v26.13.1
// TS in reverse: the tree walk is a typed recursion over readdir entries
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
const root: string = fs.mkdtempSync(path.join(os.tmpdir(), "ts_rii_a44_"));
fs.mkdirSync(path.join(root, "a", "sub"), { recursive: true });
fs.writeFileSync(path.join(root, "a", "file1.txt"), "1");
fs.writeFileSync(path.join(root, "a", "sub", "file2.txt"), "2");
fs.writeFileSync(path.join(root, "top.txt"), "3");
function walk(dir: string, acc: string[]): string[] {
for (const name of fs.readdirSync(dir).sort()) {
const p = path.join(dir, name);
if (fs.statSync(p).isDirectory()) walk(p, acc);
else acc.push(path.relative(root, p));
}
return acc;
}
console.log(walk(root, []).map((f) => f.split(path.sep).join("/")).join("\n"));
fs.rmSync(root, { recursive: true });
a/file1.txt a/sub/file2.txt top.txt
Language differences
C: POSIX nftw(3) (<ftw.h>) is the system-level tree walk - one callback per entry, FTW_DEPTH gives post-order (the example deletes bottom-up with it); Windows pairs FindFirstFile/FindNextFile recursion.
C++: the standard library's std::filesystem::recursive_directory_iterator (C++17) is the answer - one loop flattens the tree, disable_recursion_pending() skips subtrees.
C#: Directory.EnumerateFiles(root, "*", AllDirectories) (or FileSystemEnumerable) is a one-liner; lazily enumerated since .NET Core, with RecursionOptions for access-denied cases.
Go: filepath.WalkDir (1.16+) callbacks every entry in lexical order and beats the older Walk (no per-entry stat); return filepath.SkipDir to prune.
Java: Files.walk (streaming) or Files.walkFileTree (visitor pattern with enter/leave control) - the latter is the standard way to clean temp trees (the example shows both).
JavaScript: Node has no built-in tree walker - recurse readdir by hand (shown); fs.promises + withFileTypes saves the stat calls.
PHP: RecursiveIteratorIterator is the textbook case of "recursive traversal is a scenario, not a function": an outer wrapper flattens any RecursiveIterator (directory trees, nested arrays, XML) into one linear stream; LEAVES_ONLY/SELF_FIRST/CHILD_FIRST decide whether and when parents appear, getDepth() reports the level. Contrast with DirectoryIterator's single-level scan (already in the corpus): single level = that entry, trees = this one.
Python: os.walk is the NATIVE answer - yields (dirpath, dirs, files) triples, and topdown=False is post-order (files before directories when deleting); pathlib.Path.rglob is the object-oriented variant.
Rust: std has no tree walker - recurse over read_dir by hand (shown); walkdir is the ecosystem standard (lazy, prunable), and the std version makes "you own the ordering" visible.
TypeScript: the same hand-written recursion as JS; TS's value is typing the signature ((dir: string, acc: string[])) and the collected output.