#How to get Entry(s) of a directory into an ArrayList without allocating additional memory for names?

1 messages · Page 1 of 1 (latest)

sinful hinge
#

I have this function to get a directory name, list all files/dirs and append them to a list:

fn appendEntries(allocator: std.mem.Allocator, list: *std.ArrayList(Entry), dir_name: []const u8) !void {
    var dir = try fs.cwd().openIterableDir(dir_name, .{});
    defer dir.close();

    var it = dir.iterate();
    while (try it.next()) |entry| {
        if (entry.name[0] == '.') continue;
        var dest = try allocator.alloc(u8, entry.name.len);
        std.mem.copy(u8, dest, entry.name);
        try list.append(.{ .name = dest, .kind = entry.kind });
    }
}

Is there a way to do this without allocating additional memory for the names? An Entry is just a name: []const u8 and kind: fs.File.Kind. It made sense to me that since name points to some memory that I can't just magically keep it after the function returns and so I have to allocate somewhere, but I could be wrong.

boreal gulch
#

not really? It has to live somewhere, whether that be by you allocating it, or something else allocating it

#

btw, see std.mem.Allocator.dupe

sinful hinge
sinful hinge
boreal gulch
#

you'll probably find that actually doesn't work correctly

sinful hinge
#

yeah that happened, just making sure I wasn't going crazy

#

thx!

boreal gulch
#

just so you know, the way it works is that the iterator has an internal buffer, about something like [1024]u8 for the platforms I know of. Each call to next writes the directory's name to that buffer and returns a pointer to it in the Entry.

#

so each call overwrites the previous name

sinful hinge
#

ahh gotcha, that's why when doing this multiple times jumbled the previous names