Zig Cookbook

介绍

使用内存映射读取文件

创建一个文件的内存映射,并模拟对文件进行一些非顺序读取。使用内存映射意味着你只需要像索引切片一样访问数据,而不必通过 seek 来在文件中定位。

在 Windows 上,这会使用 NtCreateSectionNtMapViewOfSection; 在其他支持内存映射的操作系统上则使用 mmap (当使用 std.Io.Threaded 时)。

const std = @import("std");

const filename = "/tmp/zig-cookbook-01-02.txt";

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const file = try std.Io.Dir.cwd().createFile(io, filename, .{
        .read = true,
        .truncate = true,
        .exclusive = false, // Set to true will ensure this file is created by us
    });
    defer file.close(io);
    const content_to_write = "hello zig cookbook";

    // Before mapping the memory, we need to ensure file isn't empty
    try file.setLength(io, content_to_write.len);

    const length = try file.length(io);
    try std.testing.expectEqual(length, content_to_write.len);

    var mm = try file.createMemoryMap(io, .{ .len = content_to_write.len });
    defer mm.destroy(io);

    // Write file via mapped memory
    std.mem.copyForwards(u8, mm.memory, content_to_write);
    // Synchronize the mapped memory with the file (store it to the file)
    try mm.write(io);

    // Synchronize memory with contents of file
    try mm.read(io);
    // Read via mapped memory
    try std.testing.expectEqualStrings(content_to_write, mm.memory);
}