传递文件路径,读取文件内容,输出文件大小
const std = @import("std");
const allocator = std.heap.page_allocator;
// 打开文件,在打开后不要忘记关闭
pub fn openfile(filename: []const u8) std.fs.File.OpenError!std.fs.File {
return std.fs.cwd().openFile(filename, .{ .mode = .read_only });
}
// 读取文件内容
pub fn readFile(file: std.fs.File) !void {
const file_stat = try file.stat();
const buffer: []u8 = try allocator.alloc(u8, file_stat.size);
defer allocator.free(buffer);
const size = try file.readAll(buffer);
std.debug.print("FILE SIZE: {d} KB\n", .{@as(f32, @floatFromInt(size)) / @as(f32, 1 << 10)});
std.debug.print("{s}\n", .{buffer});
}
pub fn main() !void {
const argv = std.process.argsAlloc(allocator) catch |err| {
std.debug.print("Alloc argv error: {?}", .{err});
return;
};
defer std.process.argsFree(allocator, argv);
if (argv.len < 2) {
std.debug.print("Usage: {s} <filename...>\n", .{argv[0]});
return;
}
for (1..argv.len) |value| {
const filename = argv[value];
const file = openfile(filename) catch |err| switch (err) {
error.FileNotFound => {
std.debug.print("OPEN FILE ERROR: {?}", .{err});
return;
},
else => {
std.debug.print("I dont know what happend... {?}", .{err});
return;
},
};
defer file.close();
try readFile(file);
}
}