I’m at a bit of a loss. Trying to implement a function that takes a directory name and returns a list of all files in that directory as std.ArrayList.
So far I’ve come up with the following code:
const std = @import("std");
const DirectoryListing = @import("DirectoryListing");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const dirname: []const u8 = "/etc";
const filelist = try getDirListing(allocator, dirname);
for (filelist.items) |element| {
std.debug.print(" {s} \n", .{element});
}
}
fn getDirListing(allocator: std.mem.Allocator, directory: []const u8) !std.ArrayList([]const u8) {
var dir = try std.fs.cwd().openDir(directory, .{ .iterate = true });
defer dir.close();
var dirIterator = dir.iterate();
var files: std.ArrayList([]const u8) = .empty;
errdefer files.deinit(allocator);
while (try dirIterator.next()) |dirContent| {
if (dirContent.kind == .file) {
std.debug.print("\n{s}\n", .{dirContent.name});
files.append(allocator, dirContent.name) catch unreachable;
for (files.items) |element| {
std.debug.print("{s}, ", .{element});
}
}
}
return files;
}
Looping through the items of the returned ArrayList in the main function gets me basically just garbled output (mainly special characters).
Doing the same loop inside the function gives me the correct output but once it’s getting beyond 22 entries it all starts to fall apart and the output gets more and more garbled.
I’m pretty new to zig and would appreciate any suggestions how to fix this.