Created
March 24, 2024 10:57
-
-
Save jinzhongjia/981c366dfb041836ba2d6983a64cc131 to your computer and use it in GitHub Desktop.
examples
This file contains hidden or 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
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