*ฅ^•ﻌ•^ฅ* ✨✨  HWisnu's blog  ✨✨ о ฅ^•ﻌ•^ฅ

Write and Read file

...

...

Defining the Point Struct

defines a struct called Point with three fields:

const std   = @import("std");
const print = std.debug.print;
const stdin = std.io.getStdIn().reader();


const Point = struct {
    loc: []const u8,
    x: i32,
    y: i32,
};

main Function

defines a Point struct and creates a file called "point.txt". It then writes the point's location and coordinates to the file using the fileWrite.writer().print() function.

After writing to the file, it reads the file back using the fileRead.reader() function and prints the contents of the file to the console.

Note: The !void return type of the main function indicates that it may return an error. The try keyword is used to handle errors, and the defer keyword is used to ensure that resources are released when they are no longer needed.

Error Handling:

Resource Management:

pub fn main() !void {

    var p1: Point = undefined;
    const filename = "point.txt";
    var fileWrite = try std.fs.cwd().createFile(
        filename, 
        .{ .truncate = false}
    );

    defer fileWrite.close();
    try fileWrite.seekFromEnd(0);

    // --WRITE--
    p1.loc = "HOME";
    p1.x = 10;
    p1.y = 99;
    try fileWrite.writer().print("{s} = {d} : {d}", .{p1.loc, p1.x, p1.y});
    
    // --READ--
    var fileRead = try std.fs.cwd().openFile(filename, .{});
    defer fileRead.close();
    try fileRead.seekTo(0);
    var buffer: [1024]u8 = undefined;

    const reader = fileRead.reader();
    while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
        print("{s}\n", .{line});
    }
}

Outcome:

HOME = 10 : 99

Note:

The code assumes we input the file content via the program itself. For a variant of this code where we take user input and write to file, check this post.

#input #low level #output #programming #zig