RecursiveIteratorIterator
RecursiveIteratorIterator implements OuterIterator
把 RecursiveIterator(目录树/多维数组)拉平成线性流的外层包装器:LEAVES_ONLY 默认只出叶子,getDepth() 给层级——递归遍历是场景不是函数。
C C23
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
/* C 反向对照:nftw(3) 是系统级树遍历——每条目回调一次,
FTW_DEPTH 给出后序(这里用它自底向上删除) */
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);
/* 排序收集到的相对路径,保证输出确定 */
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++ 反向对照:recursive_directory_iterator 一个循环拉平整棵树;
// 相对化并排序,输出顺序确定
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# 反向对照:Directory.EnumerateFiles + AllDirectories 就是内建的
// 树遍历——惰性、一行搞定,过滤留在管线里
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 反向对照:filepath.WalkDir 是树遍历器——回调按字典序
// 收到每一条目;跳过目录即只见文件
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 反向对照:Files.walk 惰性流式拉平整棵树;
// 过滤常规文件并相对化用于展示
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));
// 清理:先删文件再删目录
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 反向对照:Node 没有树遍历器——手写 readdir 递归,
// 排序目录名让访问顺序确定
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 把树形 RecursiveIterator(这里是目录树)
// 拉平成一条线性流;默认 LEAVES_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() 报告当前嵌套层级(顶层 = 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";
// 清理(尽力而为):先文件后目录,自底向上
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 反向对照:os.walk 就是目录树迭代器——逐层产出
# (dirpath, dirs, files),无需任何包装器
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 反向对照:std 没有树遍历器——手写 read_dir 递归并排序,
// 让顺序确定(生态答案是 walkdir crate;std 版本把这个过程摆明)
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 反向对照:树遍历就是对 readdir 条目的带类型递归
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
语言差异说明
C:POSIX 的 nftw(3)(<ftw.h>)是系统级树遍历——回调每条目一次,FTW_DEPTH 给出后序(示例用它自底向上删除);Windows 对应 FindFirstFile/FindNextFile 递归。
C++:std::filesystem::recursive_directory_iterator(C++17)是正解——一行循环拉平树,disable_recursion_pending() 可跳子树。
C#:Directory.EnumerateFiles(root, "*", AllDirectories)(或 FileSystemEnumerable)一行流;.NET Core 起惰性枚举,访问被拒可配 RecursionOptions。
Go:filepath.WalkDir(1.16+)按字典序回调每条目,比老的 Walk 快(不对每项 stat);返回 filepath.SkipDir 跳过子树。
Java:Files.walk(流式)或 Files.walkFileTree(访问者模式,可控进出目录)——后者是清理临时目录树的标准姿势(示例两者都体现)。
JavaScript:Node 无内建树遍历——手写 readdir 递归(示例);fs.promises + withFileTypes 可省 stat 调用。
PHP:RecursiveIteratorIterator 是「递归遍历是场景不是函数」的教科书:外层包装器把任何 RecursiveIterator(目录树、多维数组、XML)拉平成线性流,LEAVES_ONLY/SELF_FIRST/CHILD_FIRST 决定父节点是否出现及何时出现,getDepth() 给层级。与 directory(A 批已有)的 DirectoryIterator 单层扫描对照:单层用前者,树用本条。
Python:os.walk 是该场景的原生答案——产出 (dirpath, dirs, files) 三元组,topdown=False 即后序(先删文件再删目录);pathlib.Path.rglob 是面向对象版。
Rust:std 无树遍历——read_dir 手写递归(示例);生态标准是 walkdir crate(惰性、可跳子树),std 版的价值在看清「顺序由你决定」。
TypeScript:同 JS 手写递归;TS 的价值是给递归签名((dir: string, acc: string[]))与产物定型。