I’m hoping someone can please tell me why this behavior is happening and how to work with it / around it. I’m just trying to get the names and paths of files and directories out of a readDirectory() function. (Zig 0.14.1)
var dir = try std.fs.Dir.openDir (std.fs.cwd(), path, .{ .iterate = true });
var walker = try dir.walk (gpa);
while (try walker.next()) |entry| {
if (!std.mem.containsAtLeast (u8, entry.path, 1, seperator)) { // don't report contents of subdirectories
stats = try std.fs.Dir.statFile (dir, entry.path);
try directories.append (DirEntry {
.name = entry.basename,
.path = entry.path,
.kind = entry.kind,
.size = stats.size,
.mode = stats.mode,
.ctime = stats.ctime,
.mtime = stats.mtime,
.atime = stats.atime
});
}
}
walker.deinit();
dir.close();
Everything works here except .name
and .path
. These are the only slices involved ([]const u8
). According to docs, walker.next()
should be returning [:0]const u8
’s and those should be automatically coerced. When I debug print entry.basename
above the .append
operation, it comes out fine. When trying to get the data out of the directories ArrayList, .name
and .path
will have the right string length, but every character in the string is character 170 (when printed as {d}
).
I can force it to work with .name = try std.fmt.allocPrint (gpa, "{s}", .{ entry.basename });
, but that allocates memory for itself and I haven’t been able to figure out how to appropriately free it in this situation or give it away to the directories ArrayList so it can be freed with that. (.toOwnedSlice()
on the whole ArrayList doesn’t do it.) Giving the slice completely to the ArrayList without allocating third-party memory for it would be perfect. This is being called and carefully managed from within a gui loop, so I’m a little boxed-in on opportunities to free awkwardly allocated memory.