glob

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

Matches paths in a directory against a shell wildcard pattern, returning a sorted array.

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"); // create empty fixtures
        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 wildcard match
            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 order is unspecified: sort for stability
    for (int i = 0; i < n; i++) {
        printf("%s\n", hits[i]);
        free((void *)hits[i]);
    }
    return 0;
}
Output
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); // create empty fixtures
    }
    std::vector<std::string> hits;
    for (const auto &e : fs::directory_iterator("d")) {
        if (e.path().extension() == ".txt") { // no glob in the standard library: hand-written match
            hits.push_back(e.path().string());
        }
    }
    std::sort(hits.begin(), hits.end());
    for (const auto &p : hits) std::cout << p << "\n";
    return 0;
}
Output
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)));
Output
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") // results come back sorted
    if err != nil {
        panic(err)
    }
    fmt.Println(strings.Join(hits, "\n"))
}
Output
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 support lives here
            for (Path p : stream) hits.add(p.toString());
        }
        Collections.sort(hits); // directory stream order is unspecified
        System.out.println(String.join("\n", hits));
    }
}
Output
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}`, "");
}
// no standard glob: hand-write listing + suffix filter
const hits = fs
  .readdirSync("d")
  .filter((f) => f.endsWith(".txt"))
  .sort()
  .map((f) => `d/${f}`);
console.log(hits.join("\n"));
Output
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() returns matches sorted
Output
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 order follows the OS, sort explicitly
Output
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();
    }
    // no glob in std: hand-written read_dir + suffix filter
    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"));
}
Output
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"));
Output
d/a.txt
d/c.txt

Language differences

C: the idiom is POSIX opendir + fnmatch (readdir order is unspecified, so sorting is mandatory).

C++: C++17 std::filesystem has no pattern matching — directory_iterator + an extension check is the hand-written equivalent.

C#: Directory.GetFiles(dir, "*.txt") (order not guaranteed — the demo adds OrderBy; recurse with EnumerationOptions).

Go: filepath.Glob (returns sorted, also no ** — recurse with filepath.WalkDir + filepath.Match).

Java: glob lives inside Files.newDirectoryStream(dir, "glob:*.txt") (unspecified order — sort it; recurse with Files.walk + getPathMatcher).

JavaScript: no glob in the standard library — Node 22+ ships an experimental fs.glob (stabilizing in newer releases), but browsers and older runtimes lack it, so ecosystems rely on minimatch/fast-glob; the teaching idiom is a hand-written "list + filter".

PHP: glob() returns [] when nothing matches and false on error (e.g. unreadable directory) — distinguish the two empties; patterns support *, ?, [abc], but no recursive ** (no such flag in PHP either — recursion is hand-written).

Python: glob.glob (order follows the filesystem, so sorted() explicitly; recursive=True enables **).

Rust: no glob in the standard library; ecosystems rely on the glob crate, and the teaching idiom is a hand-written "list + filter".

TypeScript: same as JavaScript.