Filter Files by Extension with std.mem.endsWith() in Zig
A robust and efficient way to detect .zig files when listing directory contents.
This recipe was written using Zig version
0.15.2. If this recipe is outdated, please let me know on X (@sepyke) or Bluesky (@pyk.sh).
Recently, I was building a simple library for my own, and in my build.zig I
required to list all Zig files in an examples directory and build them as
binaries. This recipe shows a robust and efficient way to detect .zig files
using std.mem.endsWith().
When you’re iterating through directory contents, you often need to check if a
file has a specific extension. Zig’s standard library provides
std.mem.endsWith() which is perfect for this. It’s efficient and clear.
Here’s how you can use it to filter for .zig files:
const std = @import("std");
const fs = std.fs;
const mem = std.mem;
const testing = std.testing;
pub fn main() !void {
// For demonstration, we'll use a temporary directory.
var tmp = testing.tmpDir(.{ .iterate = true });
defer tmp.cleanup();
const base_dir = tmp.dir;
// Create some test files.
try base_dir.writeFile(.{ .sub_path = "test.zig", .data = "// zig file" });
try base_dir.writeFile(.{ .sub_path = "another.txt", .data = "just text" });
try base_dir.writeFile(.{ .sub_path = "main.zig", .data = "// main zig file" });
std.debug.print("Filtering for .zig files:\n", .{});
var iter = base_dir.iterate();
while (try iter.next()) |entry| {
// Check if it's a file and ends with ".zig"
if (entry.kind == .file and mem.endsWith(u8, entry.name, ".zig")) {
std.debug.print("Found Zig file: {s}\n", .{entry.name});
}
}
}Make sure Zig is installed:
$ zig version
0.15.2Then run it:
$ zig run filter_by_extension.zig
Filtering for .zig files:
Found Zig file: test.zig
Found Zig file: main.zig