Leggere file in Zig
Continuando lo studio di Zig, in questo articolo vi propongo come leggere un file di testo, e stampare riga per riga il contenuto.
Considerate che sto usando la versione 0.15.2.
Questo il codice:
const std = @import("std");
pub fn main() !void {
const file_path = "/home/fermat/TEST/test.txt";
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var file = try std.fs.openFileAbsolute(file_path, .{});
defer file.close();
const content = try file.readToEndAlloc(allocator, 1024 * 1024 * 10);
defer allocator.free(content);
var lines = std.mem.splitScalar(u8, content, '\n');
var line_count: usize = 0;
std.debug.print("Contenuto del file:\n", .{});
while (lines.next()) |line| {
line_count += 1;
std.debug.print("Riga {d}: {s}\n", .{line_count, line});
}
const byte_count: usize = content.len;
std.debug.print("\n{d} lines, {d} bytes\n", .{line_count, byte_count});
}
Enjoy!
zig generalpurposeallocator openfileabsolute
Commentami!