Skip to content

Commit

Permalink
add 01-02
Browse files Browse the repository at this point in the history
  • Loading branch information
jiacai2050 committed Dec 10, 2023
1 parent 845fbaf commit bddeed3
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/01-02-mmap-file.md
Original file line number Diff line number Diff line change
@@ -1 +1,35 @@
# Mmap file

Creates a memory map of a file using mmap and simulates some non-sequential reads from the file. Using a memory map means you just index into a slice rather than dealing with seek to navigate a File.

```zig
const file = try fs.cwd().createFile(filename, .{
.read = true,
.truncate = true,
.exclusive = false, // Set to true will ensure this file is created by us
});
defer file.close();
// Before mmap, we need to ensure file isn't empty
try file.setEndPos(file_size);
const md = try file.metadata();
print("File size: {d}\n", .{md.size()});
var ptr = try std.os.mmap(
null,
20,
std.os.PROT.READ | std.os.PROT.WRITE,
std.os.MAP.PRIVATE,
file.handle,
0,
);
defer std.os.munmap(ptr);
// Write file via mmap
std.mem.copyForwards(u8, ptr, "hello zig cookbook");
// Read file via mmap
print("File body: {s}", .{ptr});
```

0 comments on commit bddeed3

Please sign in to comment.