Skip to content

Instantly share code, notes, and snippets.

@xsbee
Last active May 15, 2023 17:20
Show Gist options
  • Save xsbee/0412ae103d1f3fe7792cf08223a48c51 to your computer and use it in GitHub Desktop.
Save xsbee/0412ae103d1f3fe7792cf08223a48c51 to your computer and use it in GitHub Desktop.
Breadth-first search cheap-version of GNU find in Zig
const std = @import("std");
const allocator = std.heap.c_allocator;
const DirQueue = std.TailQueue(std.fs.IterableDir);
pub fn main() !void {
var argv = try std.process.argsWithAllocator(allocator);
defer argv.deinit();
_ = argv.skip();
const searchString: []const u8 = argv.next() orelse return;
const searchDir = argv.next() orelse ".";
const stdout = std.io.getStdOut().writer();
var dirList = DirQueue{};
dirList.append(blk: {
var node = try allocator.create(DirQueue.Node);
node.data = try std.fs.cwd().openIterableDir(searchDir, .{});
break :blk node;
});
while (true) {
var dirIterNode = dirList.popFirst() orelse break;
defer allocator.destroy(dirIterNode);
var dirIter = dirIterNode.data;
defer dirIter.close();
var iterator = dirIter.iterate();
while (try iterator.next()) |entry| {
if (entry.kind == .Directory) {
dirList.append(blk: {
var node = try allocator.create(DirQueue.Node);
node.data = try dirIter.dir.openIterableDir(entry.name, .{});
break :blk node;
});
}
var path: [std.fs.MAX_PATH_BYTES:0]u8 = undefined;
if (std.mem.eql(u8, entry.name, searchString))
try stdout.print("{s}\n", .{try dirIter.dir.realpath(entry.name, &path)});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment