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

User Input - Write and Read File

...

...

Point struct and getString function

Defines a struct called Point with three fields:

getString function reads a string from the standard input and returns a copy of the string. It takes an allocator as a parameter, which is used to allocate memory for the string.

const std        = @import("std");
const print      = std.debug.print;
const stdin      = std.io.getStdIn().reader();
const ArenaAlloc = std.heap.ArenaAllocator;
const PageAlloc  = std.heap.page_allocator;


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

fn getString(allocator: std.mem.Allocator) ![]u8 {

    var buffer: [100]u8 = undefined;
    print("\nEnter a location: ", .{});

    const input = try stdin.readUntilDelimiterOrEof(buffer[0..], '\n');
    if (input) |str| {
        return try allocator.dupe(u8, str);
    } else {
        return try allocator.dupe(u8, "");
    }
}

getInput Function

Reads an integer from the standard input and returns the integer. It takes no parameters.

fn getInput() !i32 {
    var buffer_in: [256]u8 = undefined;
    const input = try stdin.readUntilDelimiterOrEof(&buffer_in, '\n');
    const trimmedLine = std.mem.trim(u8, input.?, "\t\r\n");
    const num = try std.fmt.parseInt(i32, trimmedLine, 10);

    return num;
}

main Function

Defines a Point struct and creates a file called "point.txt". It then enters a loop where it reads a point's location and coordinates from the standard input and writes them to the file.

After writing to the file, it reads the file back and prints the points to the console.

pub fn main() !void {

    var arena = ArenaAlloc.init(PageAlloc);
    defer arena.deinit();
    const allocator = arena.allocator();

    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);

    var active: i32 = 1;
    while (active == 1) {

        // --WRITE--
        p1.loc = try getString(allocator);
        print("Enter x: ", .{});
        p1.x = try getInput();
        print("Enter y: ", .{});
        p1.y = try getInput();
        try fileWrite.writer().print("{s} = {d} : {d}\n", .{p1.loc, p1.x, p1.y});

        print("\nDo you want to continue? \n[1 for yes / 0 for no]: ", .{});
        active = try getInput();
    }
    
    // --READ--
    var fileRead = try std.fs.cwd().openFile(filename, .{});
    defer fileRead.close();
    try fileRead.seekTo(0);
    var buffer: [1024]u8 = undefined;

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

Outcome:

For instance the user inputs these values:

Enter a location: OFFICE
Enter x: 69
Enter y: -42

Result:

OFFICE = 69 : -42

#low level #programming #snippet #user input #zig