zig

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


I would like to avoid making a set size buffer because of things like a file being too big, or small enough that there is empty space in the buffer. An ArenaAllocator sounds promising since you can allocate more space as needed. Is there a "proper" way to do this, i.e. load a .json file passed as a command line argument into a buffer?


Solution

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

    You can request file's size and allocate the same amount of memory:

    const file = try std.fs.cwd().openFile("file.txt", .{}));
    defer file.close();
    
    const file_size = (try file.stat()).size;
    const buffer = try allocator.alloc(u8, file_size);
    

    Then you can read the file by using readNoEof:

    try file.reader().readNoEof(buffer);
    

    Alternatively, you can use File's readToEndAlloc function:

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