scandir

scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING, ?resource $context = null): array|false

Lists files and directories inside the specified path.

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) {
    mkdir("demo", 0755);
    FILE *fp;
    fp = fopen("demo/banana.txt", "w"); fputs("x", fp); fclose(fp);
    fp = fopen("demo/apple.txt", "w"); fputs("x", fp); fclose(fp);
    fp = fopen("demo/cherry.txt", "w"); fputs("x", fp); fclose(fp);

    DIR *dp = opendir("demo");
    if (!dp) {
        return 1;
    }
    char *names[16];
    int n = 0;
    struct dirent *ent;
    while ((ent = readdir(dp)) != NULL && n < 16) {
        names[n++] = strdup(ent->d_name); /* must strdup: readdir reuses its buffer; POSIX also lists the . .. entries */
    }
    closedir(dp);

    qsort(names, n, sizeof(char *), cmp); /* readdir order is system-defined; sort for stable output */
    for (int i = 0; i < n; i++) {
        printf("%s\n", names[i]);
    }
    return 0;
}
Output
.
..
apple.txt
banana.txt
cherry.txt

C++ C++26

C++26
#include <filesystem>
#include <fstream>
#include <iostream>
#include <set>
int main() {
    std::filesystem::create_directory("demo"); // creates a single-level directory
    for (const char *name : {"banana.txt", "apple.txt", "cherry.txt"}) {
        std::ofstream(std::string("demo/") + name) << "x";
    }

    std::set<std::string> names; // std::set sorts automatically; directory_iterator yields no . .. entries
    for (const auto &entry : std::filesystem::directory_iterator("demo")) {
        names.insert(entry.path().filename().string());
    }
    for (const auto &name : names) {
        std::cout << name << "\n";
    }
    return 0;
}
Output
apple.txt
banana.txt
cherry.txt

C# v11.0.100

v11.0.100
Directory.CreateDirectory("demo");
foreach (var name in new[] { "banana.txt", "apple.txt", "cherry.txt" }) {
    File.WriteAllText($"demo/{name}", "x");
}

foreach (var name in Directory.GetFiles("demo").Select(Path.GetFileName).OrderBy(n => n)) {
    Console.WriteLine(name); // GetFiles has no . .. entries; sort for stable output
}
Output
apple.txt
banana.txt
cherry.txt

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "os"
)

func main() {
    os.Mkdir("demo", 0755)
    for _, name := range []string{"banana.txt", "apple.txt", "cherry.txt"} {
        os.WriteFile("demo/"+name, []byte("x"), 0644)
    }

    entries, err := os.ReadDir("demo") // ReadDir returns names sorted by filename, no . .. entries
    if err != nil {
        panic(err)
    }
    for _, e := range entries {
        fmt.Println(e.Name())
    }
}
Output
apple.txt
banana.txt
cherry.txt

Java v27.0.1

v27.0.1
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Files.createDirectory(Path.of("demo"));
        for (String name : new String[]{"banana.txt", "apple.txt", "cherry.txt"}) {
            Files.writeString(Path.of("demo", name), "x");
        }

        try (var entries = Files.list(Path.of("demo"))) {
            entries.map(e -> e.getFileName().toString()).sorted().forEach(System.out::println);
        }
    }
}
Output
apple.txt
banana.txt
cherry.txt

JavaScript v26.13.1

v26.13.1
const fs = require("node:fs");
fs.mkdirSync("demo");
for (const name of ["banana.txt", "apple.txt", "cherry.txt"]) {
  fs.writeFileSync(`demo/${name}`, "x");
}

for (const name of fs.readdirSync("demo").sort()) {
  console.log(name); // readdirSync has no . .. entries; sort for stable output
}
Output
apple.txt
banana.txt
cherry.txt

PHP v8.6.0

v8.6.0
mkdir("demo");
file_put_contents("demo/banana.txt", "x");
file_put_contents("demo/apple.txt", "x");
file_put_contents("demo/cherry.txt", "x");
print_r(scandir("demo")); // ascending by default; includes the two special entries . and ..
Output
Array
(
    [0] => .
    [1] => ..
    [2] => apple.txt
    [3] => banana.txt
    [4] => cherry.txt
)

Python v3.15.2

v3.15.2
import os

os.mkdir("demo")
for name in ("banana.txt", "apple.txt", "cherry.txt"):
    with open(f"demo/{name}", "w") as f:
        f.write("x")

# os.listdir has no . .. entries; os.scandir returns DirEntry objects with cached stat
for name in sorted(os.listdir("demo")):
    print(name)
Output
apple.txt
banana.txt
cherry.txt

Rust v1.99.1

v1.99.1
use std::fs;

fn main() {
    fs::create_dir("demo").unwrap();
    for name in ["banana.txt", "apple.txt", "cherry.txt"] {
        fs::write(format!("demo/{name}"), "x").unwrap();
    }

    let mut names: Vec<String> = fs::read_dir("demo").unwrap() // read_dir yields no . .. entries
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort(); // the OS makes no ordering promise; sort for stable output
    for name in names {
        println!("{name}");
    }
}
Output
apple.txt
banana.txt
cherry.txt

TypeScript v26.13.1

v26.13.1
import * as fs from "node:fs";
fs.mkdirSync("demo");
for (const name of ["banana.txt", "apple.txt", "cherry.txt"] as const) {
  fs.writeFileSync(`demo/${name}`, "x");
}

for (const name of fs.readdirSync("demo").sort()) {
  console.log(name);
}
Output
apple.txt
banana.txt
cherry.txt

Language differences

C: POSIX readdir includes . and ..; the returned d_name points into reused internal storage, so strdup before keeping it.

C++: C++17 directory_iterator omits ./...

C#: Directory.GetFiles omits ./..; order not guaranteed — the example sorts with OrderBy for determinism.

Go: os.ReadDir omits ./..; already sorted by filename.

Java: Files.list omits ./..; ordering not guaranteed — sort it; prefer Files.list (a lazy stream closed via try-with-resources).

JavaScript: fs.readdirSync omits ./..; ordering not guaranteed — sort it.

PHP: the big semantic split — scandir includes the . and .. special entries (normalize that first when comparing across languages); ordering: sorts ascending by default (pass SCANDIR_SORT_DESCENDING to flip).

Python: os.listdir/os.scandir omit ./..; ordering is filesystem-dependent — the example sorts with sorted(); efficiency note: os.scandir returns DirEntry objects with cached stat data, saving syscalls when walking trees.

Rust: fs::read_dir omits ./..; DirEntry::file_type() avoids an extra stat.

TypeScript: same as JS — fs.readdirSync.