-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
845fbaf
commit bddeed3
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}); | ||
``` |