如何创建与文件大小相同的缓冲区?

How can you create a buffer of the same size as a file?

我想避免创建一个设置大小的缓冲区,因为诸如文件太大或足够小以至于缓冲区中有空 space 之类的事情。 ArenaAllocator 听起来很有希望,因为您可以根据需要分配更多 space。是否有“正确”的方法来执行此操作,即将作为命令行参数传递的 .json 文件加载到缓冲区中?

使用 GeneralPurposeAllocator。您可以在 https://youtu.be/vHWiDx_l4V0

中了解有关分配器的更多信息
const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = &gpa.allocator;
    const args = try std.process.argsAlloc(allocator);
    defer std.process.argsFree(allocator, args);
    const file = try std.fs.cwd().openFile(args[1], .{});
    const file_content = try file.readToEndAlloc(allocator, 1024 * 1024); // 1MB max read size
    defer allocator.free(file_content);
    std.debug.print("{s}", .{file_content});
}

How can you create a buffer of the same size as a file?

您可以请求文件大小并分配相同数量的内存:

var file = try std.fs.cwd().openFile("file.txt", .{ open = true }));

const file_size = (try file.stat()).size;
var buffer = try allocator.alloc(u8, file_size);

然后您可以使用 readNoEof:

读取文件
try file.reader().readNoEof(buffer);

或者,您可以使用 FilereadToEndAlloc 函数:

const size_limit = std.math.maxInt(u32); // or any other suitable limit
var result = try file.readToEndAlloc(allocator, size_limit);

在 0.10.0-dev.2345+9747303d1 上,这对我有用:

const std = @import("std");

pub fn main() !void {
    var file = try std.fs.cwd().openFile("test.ts", .{ .mode = .read_only });
    const file_size = (try file.stat()).size;
    const allocator = std.heap.page_allocator;
    var buffer = try allocator.alloc(u8, file_size);
    try file.reader().readNoEof(buffer);

    std.debug.print("{s}\n", .{buffer});
}

OpenFlags for .openFile 定义如下: https://github.com/ziglang/zig/blob/master/lib/std/fs/file.zig#L80