Skip to content

Instantly share code, notes, and snippets.

@jinzhongjia
Created March 24, 2024 10:57
Show Gist options
  • Save jinzhongjia/981c366dfb041836ba2d6983a64cc131 to your computer and use it in GitHub Desktop.
Save jinzhongjia/981c366dfb041836ba2d6983a64cc131 to your computer and use it in GitHub Desktop.
examples
const std = @import("std");
pub fn readFile(fp: []const u8) !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
// 拿到一个allocator
const allocator = gpa.allocator();
// defer 用于执行general_purpose_allocator善后工作
defer {
const deinit_status = gpa.deinit();
if (deinit_status == .leak) @panic("TEST FAIL");
}
const fmt = std.io.getStdOut().writer();
if (std.fs.cwd().openFile(fp, .{})) |file| {
defer file.close();
const stat = try file.stat();
const buf = try allocator.alloc(u8, stat.size);
defer allocator.free(buf);
try file.seekTo(0);
const i = try file.readAll(buf);
try fmt.print("read length is {}\n", .{i});
try fmt.print("file's content is {s}\n", .{buf});
} else |err| {
try fmt.print("open {s}: {}\n", .{ fp, err });
}
}
pub fn main() !void {
try readFile("1.txt");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment