glob

glob(string $pattern, int $flags = 0): array|false

按 shell 通配模式匹配目录下的路径,返回排序后的数组。

C C23

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

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

int main(void) {
    mkdir("d", 0755);
    const char *names[] = {"a.txt", "b.log", "c.txt"};
    for (int i = 0; i < 3; i++) {
        char path[64];
        snprintf(path, sizeof path, "d/%s", names[i]);
        FILE *f = fopen(path, "w"); // 建空测试文件
        if (f) fclose(f);
    }
    DIR *dp = opendir("d");
    const char *hits[8];
    int n = 0;
    struct dirent *ent;
    while ((ent = readdir(dp)) != NULL) {
        if (fnmatch("*.txt", ent->d_name, 0) == 0) { // POSIX 通配匹配
            char full[64];
            snprintf(full, sizeof full, "d/%s", ent->d_name);
            hits[n++] = strdup(full);
        }
    }
    closedir(dp);
    qsort(hits, n, sizeof hits[0], cmp_str); // readdir 顺序不定:排序保证稳定
    for (int i = 0; i < n; i++) {
        printf("%s\n", hits[i]);
        free((void *)hits[i]);
    }
    return 0;
}
输出
d/a.txt
d/c.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::create_directories("d");
    for (const char *name : {"a.txt", "b.log", "c.txt"}) {
        std::ofstream(fs::path("d") / name); // 建空测试文件
    }
    std::vector<std::string> hits;
    for (const auto &e : fs::directory_iterator("d")) {
        if (e.path().extension() == ".txt") { // 标准库无 glob:手写匹配
            hits.push_back(e.path().string());
        }
    }
    std::sort(hits.begin(), hits.end());
    for (const auto &p : hits) std::cout << p << "\n";
    return 0;
}
输出
d/a.txt
d/c.txt

C# v11.0.100

v11.0.100
using System;
using System.IO;
using System.Linq;

Directory.CreateDirectory("d");
foreach (string name in new[] { "a.txt", "b.log", "c.txt" })
{
    File.WriteAllText(Path.Combine("d", name), "");
}
Console.WriteLine(string.Join("\n", Directory.GetFiles("d", "*.txt").OrderBy(p => p)));
输出
d/a.txt
d/c.txt

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "os"
    "path/filepath"
    "strings"
)

func main() {
    if err := os.Mkdir("d", 0755); err != nil && !os.IsExist(err) {
        panic(err)
    }
    for _, name := range []string{"a.txt", "b.log", "c.txt"} {
        if err := os.WriteFile(filepath.Join("d", name), nil, 0644); err != nil {
            panic(err)
        }
    }
    hits, err := filepath.Glob("d/*.txt") // 结果已排序
    if err != nil {
        panic(err)
    }
    fmt.Println(strings.Join(hits, "\n"))
}
输出
d/a.txt
d/c.txt

Java v27.0.1

v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {
        Path dir = Path.of("d");
        Files.createDirectories(dir);
        for (String name : new String[] {"a.txt", "b.log", "c.txt"}) {
            Files.writeString(dir.resolve(name), "");
        }
        List<String> hits = new ArrayList<>();
        try (var stream = Files.newDirectoryStream(dir, "*.txt")) { // glob 能力在这里
            for (Path p : stream) hits.add(p.toString());
        }
        Collections.sort(hits); // 目录流顺序不保证
        System.out.println(String.join("\n", hits));
    }
}
输出
d/a.txt
d/c.txt

JavaScript v26.13.1

v26.13.1
const fs = require("node:fs");

fs.mkdirSync("d", { recursive: true });
for (const name of ["a.txt", "b.log", "c.txt"]) {
  fs.writeFileSync(`d/${name}`, "");
}
// 无标准 glob:手写 目录列表 + 后缀过滤
const hits = fs
  .readdirSync("d")
  .filter((f) => f.endsWith(".txt"))
  .sort()
  .map((f) => `d/${f}`);
console.log(hits.join("\n"));
输出
d/a.txt
d/c.txt

PHP v8.6.0

v8.6.0
mkdir("d");
foreach (["a.txt", "b.log", "c.txt"] as $name) {
    file_put_contents("d/$name", "");
}
echo implode("\n", glob("d/*.txt")); // glob() 返回已排序的匹配
输出
d/a.txt
d/c.txt

Python v3.15.2

v3.15.2
import glob
from pathlib import Path

Path("d").mkdir(exist_ok=True)
for name in ("a.txt", "b.log", "c.txt"):
    Path("d", name).touch()
print("\n".join(sorted(glob.glob("d/*.txt"))))  # glob 顺序跟随系统,显式排序
输出
d/a.txt
d/c.txt

Rust v1.99.1

v1.99.1
use std::fs;

fn main() {
    fs::create_dir_all("d").unwrap();
    for name in ["a.txt", "b.log", "c.txt"] {
        fs::write(format!("d/{name}"), "").unwrap();
    }
    // 标准库无 glob:手写 read_dir + 后缀过滤
    let mut hits: Vec<String> = fs::read_dir("d")
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .filter(|n| n.ends_with(".txt"))
        .map(|n| format!("d/{n}"))
        .collect();
    hits.sort();
    println!("{}", hits.join("\n"));
}
输出
d/a.txt
d/c.txt

TypeScript v26.13.1

v26.13.1
import * as fs from "node:fs";

fs.mkdirSync("d", { recursive: true });
for (const name of ["a.txt", "b.log", "c.txt"]) {
  fs.writeFileSync(`d/${name}`, "");
}
const hits = fs
  .readdirSync("d")
  .filter((f) => f.endsWith(".txt"))
  .sort()
  .map((f) => `d/${f}`);
console.log(hits.join("\n"));
输出
d/a.txt
d/c.txt

语言差异说明

C:惯用法是 POSIX opendir + fnmatch(readdir 顺序不定必须排序)。

C++:C++17 std::filesystem 没有模式匹配,directory_iterator + 扩展名判断是等价手写。

C#:Directory.GetFiles(dir, "*.txt")(顺序不保证,演示里加了 OrderBy;递归用 EnumerationOptions)。

Go:filepath.Glob(返回已排序,同样不支持 **,递归用 filepath.WalkDir + filepath.Match)。

Java:glob 藏在 Files.newDirectoryStream(dir, "glob:*.txt")(顺序不保证要自己排;递归用 Files.walk 配 getPathMatcher)。

JavaScript:标准库没有 glob——Node 22 起提供实验性 fs.glob(新版本逐步稳定),跨版本与浏览器仍无标准,生态靠 minimatch/fast-glob,教学姿势是「列表 + 过滤」手写。

PHP:glob() 匹配不到返回 []、出错(如目录不可读)返回 false——两种空要区分;模式支持 *、?、[abc],但不支持 ** 递归(PHP 没有 GLOB_RECURSE 这类开关,递归需手写或用迭代器)。

Python:glob.glob(顺序跟随文件系统、必须显式 sorted();recursive=True 配 ** 才递归)。

Rust:标准库没有 glob,生态靠 glob crate,教学姿势是「列表 + 过滤」手写。

TypeScript:同 JavaScript。